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

时间:2019-11-18 20:43:28

标签: angular ngrx 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);

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

2 个答案:

答案 0 :(得分:0)

请尝试以下代码

   <table>
     <tr>
         <th>ID</th>
         <th>Name</th>
      </tr>
        <tbody *ngFor="let item of groupArr">
             <ng-container>
        <tr >
          <td colspan="2"><b>{{item.group}}</b></td>
        </tr>
        <tr *ngFor="let value of item.groupItem">
          <td>{{value.name}}</td>
        </tr>
      </ng-container></tbody>
   </table>

答案 1 :(得分:0)

您必须创建一个 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)

  }