我如何 POST 来自输入和结果数据的数据显示到 Angular 中的组件?

How I POST data from input and result data display to component in Angular?

我 POST 从输入到服务器的组件中的显示数据有问题。在输入中,我需要输入 companyId,然后 POST 请求服务器 return 来自产品的特定数据。在控制台中,我从服务器得到响应,它是 undefined 但在网络选项卡中,我看到 POST 成功并且数据来自服务器,我不知道如何捕获和显示它们。

JSON:

{"products":[{"productId":"4","productName":"Trucker Classic 6","productCode":"TGP11136C","productGroupMiddleName":"Truckih","resourceUrl":"\/Product\/4","installmentTypes":[{"installmentTypeId":"1","installmentTypeName":"Single premium"},{"installmentTypeId":"2","installmentTypeName":"Annual instalments"}]}, {"productId":"5","productName":"Trucken Classic 8","productCode":"TGP48145C","productGroupMiddleName":"Truck4","resourceUrl":"\/Product\/5","installmentTypes":[{"installmentTypeId":"1","installmentTypeName":"Single premium"},{"installmentTypeId":"2","installmentTypeName":"Annual instalments"}]},{"productId":"6","productName":"Truckel Classic 6","productCode":"TAP60562C","productGroupMiddleName":"Truck8","resourceUrl":"\/Product\/6","installmentTypes":[{"installmentTypeId":"1","installmentTypeName":"Single premium"},{"installmentTypeId":"2","installmentTypeName":"Annual instalments"}]},

代码:

component.ts

testForm: FormGroup;
product: Products[] = [];

 constructor(
    private testService: testService,
  ) {
  }

ngOnInit(): void { 
    this.testForm = new FormGroup({
      productId: new FormControl()
    });
  }

submit() {
    this.testService.searchByProduct(this.testForm.value).subscribe(
        (response: any) => {
        this.product = response.products;
        console.log(this.product);
        },
        (error: any) => {
          console.error(error);
        });
  }

component.html

    <form fxLayout="column" fxLayoutGap="10px" [formGroup]="testForm" (submit)="submit()" class="form">
      <mat-form-field appearance="fill">
        <mat-label>ID product</mat-label>
        <input matInput id="productId" type="number" formControlName="productId">
      </mat-form-field>
    
      <button mat-raised-button class="form-button" color="primary" type="submit">search</button>
    </form>

**<!--- I NEED TO SHOW RESPONSE DATA HERE --->**
        <div *ngFor="let i of product">
          <p>{{i.productId}}</p>
          <p>{{i.productName}}</p>
        </div>

model.ts

export class Products {
  productId: number;
  productName: string;
  productCode: string;
}

service.ts

searchByProduct(productId) {
    return this.http.post(environment.ApiUrl + '/api/urlapi', productId, {responseType: 'text'});
  }

我看到了几个问题,但我不确定为什么 response 应该是未定义的。

  • 你的 searchByProduct 方法 returns 类型 stringObservable 因为你在第二个参数中传递了 responseType: 'text',但你想要产品作为 Javascript 对象。删除 responseType,响应将被解析为对象
  • 我认为 this.testForm.value 将直接计算为 { productId: **/some number**/} 而不是数字