6

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());
  }
Fatih
  • 121
  • 1
  • 2
  • 14

5 Answers5

20

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.

Marco Barbero
  • 1,460
  • 1
  • 12
  • 22
4

"then" is a promise concept, RxJS is a bit different. If you want to sequence multiple calls, then you need to use forkJoin. If you just want to have a success handler, then use subscribe and catch.

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

Make sure you understand the difference between promise and observable (Angular - Promise vs Observable) and make appropriate design decision.

NitinSingh
  • 2,029
  • 1
  • 15
  • 33
1

I solved it by using toPromise() function like this:

  getUsers(){
    this.authService.getUsers().toPromise().then((res) => {
      this.user = res;
      console.log(this.user);
    },(err) => {
      console.log(err);
    });
  }
Tomislav Stankovic
  • 3,080
  • 17
  • 35
  • 42
0

Try something like this.

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

...

this.yourService.getWhatYouWant()
.map(data => {
  // do some thing
})
.toPromise()
.catch(err => {
  // handle error
});
Anuradha Gunasekara
  • 6,553
  • 2
  • 27
  • 37
-1

For use toPromise().then(), first is necesary to get the Object of Observable
I use this solution:

   import { of } from "rxjs";
----------------

 var clienteDocument = this.clienteCollection.doc(nuevocliente.cli_cedula);
    var clienteObservable = clienteDocument.valueChanges(); //Get Observable<Object> from Firebase
    var cliente = of(clienteObservable); //Obtengo el Objeto de Observable
    cliente.toPromise().then((cliente) => {  
      if (cliente == null) {
        //cliente not existe

      } else {
        //cliente exist :)

      }
    });
Shoniisra
  • 621
  • 7
  • 6