您必须创建一个 DataService 类并使用这样的自定义更新功能。
@Injectable()
export class PromotionDataService extends DefaultDataService<Promotion> {
httpClient: HttpClient;
constructor(httpClient: HttpClient, httpUrlGenerator: HttpUrlGenerator) {
super('Promotion', httpClient, httpUrlGenerator);
this.httpClient = httpClient;
}
updatePromotion(promotionId: string, formData: FormData): Observable<Promotion> {
formData.append('_method', 'PUT');
return this.httpClient.post(`${environment.apiUrl}/api/v1/manager/promotion/` + promotionId, formData)
.pipe(map((response: Promotion) => {
return response;
}));
}
}
我正在使用 post 请求,因为 put 请求不适用于 multipart/form-data。然后注册数据服务如下。
@NgModule({
providers: [
PromotionDataService
]
})
export class EntityStoreModule {
constructor(
entityDataService: EntityDataService,
promotionDataService: PromotionDataService,
) {
entityDataService.registerService('Promotion', promotionDataService);
}
}
@NgModule({
declarations: [
PromotionComponent,
],
exports: [
],
imports: [
EntityStoreModule
],
})
export class PromotionModule {}
在您的组件中首先在构造函数中注入数据服务,然后您可以像这样使用自定义更新功能
onSubmit() {
if (this.promotionForm.invalid) {
return;
}
const newPromotion: Promotion = this.promotionForm.value;
const fileControl = this.f.banner;
let files: File[];
let file: File = null;
if(fileControl.value){
files = fileControl.value._files
}
if(files && files.length > 0) {
file = files[0];
}
const formData = new FormData();
if(file != null){
formData.append('banner', file, file.name);
}
formData.append('data', JSON.stringify(newPromotion));
this.service.updatePromotion(promotion.id, formData)
}