问题描述
每次我提交没有图像的帖子时都会收到错误,提交图像是可选的,因为我在附加 imagePath 之前运行了 if
条件。正在研究一个我不熟悉的 MEAN 堆栈。
mime-type-validator
import { AbstractControl } from "@angular/forms";
import { Observable,Observer,of } from "rxjs";
export const mimeType = (
control: AbstractControl
): Promise<{ [key: string]: any }> | Observable<{ [key: string]: any }> => {
if (typeof(control.value) === 'string') {
return of(null);
}
const file = control.value as File;
const fileReader = new FileReader();
const frObs = Observable.create(
(observer: Observer<{ [key: string]: any }>) => {
fileReader.addEventListener("loadend",() => {
const arr = new Uint8Array(fileReader.result as ArrayBuffer).subarray(0,4);
let header = "";
let isValid = false;
for (let i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
switch (header) {
case "89504e47":
isValid = true;
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
case "ffd8ffe3":
case "ffd8ffe8":
isValid = true;
break;
default:
isValid = false; // Or you can use the blob.type as fallback
break;
}
if (isValid) {
observer.next(null);
} else {
observer.next({ invalidMimeType: true });
}
observer.complete();
});
fileReader.readAsArrayBuffer(file);
}
);
return frObs;
};
创建后组件
import { Component,Inject,Input,OnInit} from '@angular/core';
import { ActivatedRoute,ParamMap } from '@angular/router';
import { FormControl,FormGroup,Validators } from '@angular/forms'
import { PostModel } from 'src/app/Models/post.model';
import { PostsService } from 'src/app/Services/posts.service';
import { Router } from '@angular/router'
import { mimeType } from 'src/app/auth/Validators/mime-type.validator'
import Swal from 'sweetalert2';
@Component({
selector: 'app-create-post',templateUrl: './create-post.component.html',styleUrls: ['./create-post.component.css']
})
export class CreatePostComponent {
public mode = 'user';
private postId : string;
public post: PostModel;
isLoading : boolean = false;
imagePreview: string;
PostForm = new FormGroup({
title: new FormControl('',[Validators.required,Validators.minLength(1),Validators.maxLength(30)]),content: new FormControl('',Validators.minLength(1)]),image: new FormControl(null,{validators:[],asyncValidators: [mimeType] })
})
constructor(public postsService: PostsService,public route: ActivatedRoute,private router: Router){
}
ngOnInit(){
this.route.paramMap.subscribe((paramMap: ParamMap)=>{
if(paramMap.has('postId')){
this.mode = 'edit';
this.postId = paramMap.get('postId');
this.isLoading = true;
this.postsService.getPost(this.postId).subscribe(postdata =>{
this.isLoading = false;
this.post = {id: postdata._id,title: postdata.title,content: postdata.content,imagePath: postdata.imagePath};
this.PostForm.setValue({ title: this.post.title,content: this.post.content,image: this.post.imagePath });
});
}
else{
this.mode = 'user';
this.postId = null;
}
})
}
onAddPost()
{
if(this.PostForm.invalid){
return;
}
this.isLoading = true;
if (this.mode === 'user'){
this.postsService.addPosts(this.PostForm.value.title,this.PostForm.value.content,this.PostForm.value.image)
this.isLoading = false;
Swal.fire({
position: 'center',icon: 'success',title: 'Post added!',showConfirmButton: false,timer: 2000
})
}
else{
this.postsService.updatePosts(
this.postId,this.PostForm.value.title,this.PostForm.value.image
);
this.router.navigateByUrl('/user');
}
this.PostForm.reset();
}
onImagePicked(event: Event){
const file = (event.target as HTMLInputElement).files[0];
this.PostForm.patchValue({image: file});
this.PostForm.get('image').updateValueAndValidity();
const reader = new FileReader();
reader.onload = () => {
this.imagePreview = reader.result as string;
};
reader.readAsDataURL(file);
}
}
posts-service.ts
import { Injectable } from '@angular/core';
import { PostModel } from '../Models/post.model';
import { HttpClient } from '@angular/common/http'
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators'
@Injectable(
{ providedIn: 'root' }
)
export class PostsService {
constructor(private http: HttpClient) { }
private posts: PostModel[] = [];
private postsUpdated = new Subject<PostModel[]>()
getPosts() {
this.http.get<{ message: string,posts: any }>('http://localhost:3300/api/posts')
.pipe(
map((postData) => {
return postData.posts.map(post => {
return {
title: post.title,content: post.content,id: post._id,imagePath: post.imagePath
}
})
}))
.subscribe(transformedPosts => {
this.posts = transformedPosts;
this.postsUpdated.next([...this.posts]) //updating the posts so that it is available to the rest of the app
})
}
getUpdatedPostsListener() {
return this.postsUpdated.asObservable()
}
getPost(id: string) {
// return {...this.posts.find( p => p.id === id)} //p implies each post,and p.id implies that post's id
return this.http.get<{ _id: string; title: string; content: string,imagePath: string }>("http://localhost:3300/api/posts/" + id);
}
addPosts(title: string,content: string,image: File) {
const postData = new FormData();
postData.append('title',title);
postData.append('content',content);
if(image != undefined){
postData.append('image',image,title);
}
this.http.post<{ message: string,post: PostModel }>('http://localhost:3300/api/posts',postData).subscribe((responseData) => {
const post: PostModel = { id: responseData.post.id,title: title,content: content,imagePath: responseData.post.imagePath }
this.posts.push(post);
this.postsUpdated.next([...this.posts]);
})
}
updatePosts(id: string,title: string,image: File | string) {
let postData: PostModel | FormData;
if (typeof image === "object") {
postData = new FormData();
postData.append("id",id);
postData.append("title",title);
postData.append("content",content);
if(image != undefined){
postData.append("image",title);
}
} else {
postData = {
id: id,imagePath: image
};
}
this.http
.put("http://localhost:3300/api/posts/" + id,postData)
.subscribe(response => {
const updatedPosts = [...this.posts];
const oldPostIndex = updatedPosts.findindex(p => p.id === id);
const post: PostModel = {
id: id,imagePath: ""
};
updatedPosts[oldPostIndex] = post;
this.posts = updatedPosts;
this.postsUpdated.next([...this.posts]);
// this.router.navigate(["/"]);
});
}
deletePosts(postId: string) {
this.http.delete('http://localhost:3300/api/posts/' + postId)
.subscribe(() => {
const updatedPosts = this.posts.filter(post => post.id !== postId);
this.posts = updatedPosts;
this.postsUpdated.next([...this.posts]);
})
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)