1

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:

enter image description here

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?

1
  • 1
    You should be getting data the Rxjs way using functional operators Commented Jun 9, 2021 at 9:20

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.