Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 : Property 'then' does not exist on type 'Observable<any>'

Tags:

angular

mean

I got this error message "[ts] Property 'then' does not exist on type 'Observable'.", how to solve it?

This is my Component :

  getUsers(){
    this.authService.getUsers().then((res) => {
      this.user = res;
      console.log(this.user);
    },(err) => {
      console.log(err);
    });
  }

This is my Service :

 getUsers(){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.get('http://192.168.100.6:3000/users/data-tracer', {headers: headers})
    .map(res => res.json());
  }
like image 897
Fatih Avatar asked Apr 10 '18 04:04

Fatih


1 Answers

You can call then on a Promise object, so because your service returns an Obaservable object, you need to transform into a Promise with the toPromise() method and use catch method to manage error in this way:

getUsers(){
    this.authService.getUsers()
    .toPromise()
    .then((res) => {
      this.user = res;
      console.log(this.user);
    })
    .catch(err=> { console.log(err) });
  }

Here you can see a DEMO. That's all.

like image 59
Marco Barbero Avatar answered Oct 14 '22 17:10

Marco Barbero