Pablots99
Pablots99

Reputation: 5

Iterating an interface array with `forEach()`

I'm new to Typescript and I'd like to save the response of an HTTP GET to an array of a type defined by an interface.

getErrors() {
  return this.http.get<ErrorsInterface[]>(environment.apiUrl+'errors').toPromise()
}

Then I declare the array like this and call the function getErrors()

errorsData: ErrorsInterface[]= []

this.errorsData = await this.ErrorsService.getErrors()
this.errorsData.forEach(res => {
 console.log(res.number)
})

But I receive the following error:

ERROR Error: Uncaught (in promise): TypeError: this.errorsData.forEach is not a function TypeError: this.errorsData.forEach is not a function

I appreciate any help

Upvotes: 0

Views: 474

Answers (2)

Awabil George
Awabil George

Reputation: 310

//in your service file

getErrors():Observable<ErrorInterface[]> {
      return this.http.get<ErrorsInterface[]>(environment.apiUrl+'errors')
  }

 private errorsData= []


getErrors(){
this.ErrorsService.getErrors().Subscribe(res=> 
this.errorsData=res
)
//console.log(this.errorsData.length)
}

Upvotes: 0

Barremian
Barremian

Reputation: 31135

I don't see the need to convert the observable to a promise here. You could make do just with the observable

Service

getErrors(): Observable<any> {  // <-- return observable
  return this.http.get<ErrorsInterface[]>(environment.apiUrl+'errors');
}

Component

errorsData: ErrorsInterface[]= []

this.ErrorsService.getErrors().subscribe({
  next: (res: any) => {
    this.errorsData = res;
    this.errorsData.forEach(error => {
      console.log(error.number)
    });
  }
  error: (error: any) => {
    // handle error
  }
);

Note:

  1. You cannot convert an asynchronous fetch to a synchronous one. Any statements (like the forEach) that depend on the async data must be inside the subscription. More info about async data here.

  2. toPromise() is being deprecated in RxJS 7 and might be gone in RxJS

Upvotes: 1

Related Questions