簡體   English   中英

無法使用 multipart/formdata 更新實體 - NgRx 數據

[英]Not able to update entity with multipart/formdata - NgRx Data

我正在嘗試更新我的一個也具有文件上傳功能的實體。 我可以使用 add 方法發送(添加)FormData,但無法更新。 NgRx 給出以下錯誤:

錯誤:主鍵不能為空/未定義。

這甚至可能嗎? 還是我做錯了什么。 請看下面的代碼:

 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 class 並像這樣使用自定義更新 function。

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

在您的組件中首先在構造函數中注入數據服務,然后您可以像這樣使用自定義更新 function

  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)

  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM