无法使用multipart/formdata更新实体-NgRx数据



我正在尝试更新我的一个实体,该实体也具有文件上传功能。我可以使用add方法发送(添加(FormData,但无法更新。NgRx给出以下错误:

错误:主键不能为null/未定义。

这可能吗?或者我做错了什么。请看下面的代码:

const ad = {
id: form.id,
accountId: this.accountId
}
const data = new FormData();
data.append('ad', JSON.stringify(ad));
// photos is an array of uploaded files
if(this.photos.length) {
this.photos.forEach(photo => {
data.append('offure_ad', photo, photo['name']);
});
}
// NgRx Data update mothod
this.adService.update(data);

请指引我往正确的方向走。谢谢

尝试以下代码

const ad = {
id: form.id,
accountId: this.accountId
}
const data = new FormData();
data.append('ad', JSON.stringify(ad));
// photos is an array of uploaded files
if(this.photos.length) {
this.photos.forEach(photo => {
data.append('offure_ad', photo, photo['name']);
});
}
// send ad like below
this.adService.update(data,ad);

您必须创建一个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-request,因为put请求不适用于multipart/form数据。然后按照以下步骤注册数据服务。

@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)
}

最新更新