1

我正在尝试更新我的一个也具有文件上传功能的实体。我可以使用 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);

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

4

2 回答 2

1

试试下面的代码

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);

于 2019-11-18T20:52:41.767 回答
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)

  }
于 2021-01-08T01:28:04.433 回答