frod_junior
frod_junior

Reputation: 115

Consuming a REST API using Angular Observable

I recently created a rest API using flask , now when I tried to use it with my Angular web App , I am receiving these errors ( I Tried to follow the same steps mentioned in the official docs : https://angular.io/tutorial/toh-pt6 )

getBills(): void {
          this.BillService.getBills()
             .subscribe(bills => this.billData=bills);
      }
       }

the error is :

ERROR in ../src/app/Bills/add-new-bill.component.ts (61,31): Type '{} | BillModel[]' is not assignable to type 'BillModel[]'. Type '{} | BillModel[]' is not assignable to type 'BillModel[]'. Type '{}' is not assignable to type 'BillModel[]'. Property 'includes' is missing in type '{}'.

this is my bill.service code :

getBills() {
    return this.http.get<BillModel[]>('http://localhost:5000/bills/123')
        .pipe(
            catchError(this.handleError('getBills'))
        );
}

and this is the model Class for my bill object :

export class BillModel {
    Amount: number;
    Bill_id: number;
    CreatedAt: string;
    From: string;
    PaymentDate: string;
    PaymentStatus: boolean;
    To: string;
};

and it works perfectly but I want to work with the observable mechanism so would u please help or explain to me why I am getting that kind of error

Upvotes: 1

Views: 442

Answers (1)

Tomasz Kula
Tomasz Kula

Reputation: 16837

You need to pass the second argument to the this.handleError method.

getBills() {
    return this.http.get<BillModel[]>('http://localhost:5000/bills/123')
        .pipe(
            catchError(this.handleError('getBills', []))
        );
}

If you do not pass the second argument to the error handler and the http observable throws, your catchError operator will return observable of undefined.

private handleError<T> (operation = 'operation', result?: T) {
  return (error: any): Observable<T> => {
    return of(result as T);
  };
}

So right now the return type of your getBills() method is actually BillModel[] | undefined. And you cannot assign that to the bills property.

Upvotes: 2

Related Questions