简体   繁体   中英

How to assign variables to data passed through a WEB API in Angular?

I am consuming a WEB API endpoint that returns product data. However, upon subscribing, I want to assign variables to this data to be used as part of a bar chart generated using Chart.js (Not relevant).

The data that is returned can be seen as follows:

在此处输入图像描述

What I have tried is the following:

generateReport() {
    if(this.service.reportForm.valid) {
      this.service.getData().subscribe
      (res => {
        console.log(res)
        let productNames = res['reportData'].map(res => res.ProductName);
        let avgQuantityOrdereed = res['reportData'].map(res => res.AverageQuantityOrdered);
        let orderQuantity = res['reportData'].map(res => res.ProductOrders.orderQuantity)
      })
    }
  }

However, I get the error: "Element implicitly has an 'any' type because expression of type '"reportData"' can't be used to index type 'Object'" under the "res['reportData'].

Is there any alternative way to doing what i tried above? And also, what is wrong with the way i did it?

Using rxjs functional operators, you can achieve the same thing with:

export class ReportComponent {
 clickObservable$: Observable<Event> = fromEvent(document,'click');
 generateReport$: Observable<string[]> = this.clickObservable$.pipe(
        filter(t => this.service.reportForm.valid),
        switchMap(t => this.service.getData()),
        map(t => t.reportData),
        map(t => t.productNames)
  )
}

HTML Template

 <ul>
    <li *ngFor="let productName of generateReport$ | async">
       {{ productName }}
    </li>
 </ul>

I realized that i simply needed to pass 'res' as a type of any:

generateReport() {
    if(this.service.reportForm.valid) {
      this.service.getData().subscribe
      ((res:any) => {
        console.log(res)
        let productNames = res['reportData'].map((res: any) => res.ProductName);
        let avgQuantityOrdereed = res['reportData'].map((res: any) => res.AverageQuantityOrdered);
        let orderQuantity = res['reportData'].map((res: any) => res.ProductOrders.orderQuantity)
        console.log(productNames)
      })
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM