user2175783
user2175783

Reputation: 1441

How to convert from observable to promise in angular

I want to create a promise out of an observable. I have the following two functions

public getData(info: Info): Promise<Data> {
   return new Promise((resolve,reject) => {
     this.getObsData(info).subscribe((data:Data) => {
       resolve(data);
       }
   });
}

getObsData(info: Info): Observable<Data> {
    this.anhttpservice(a,b,c).switchMap(data=>
     return Observable.create(observer=> {observer.next(new Data(data))});
    }
}

I keep getting an error from getObsData() as shown below.

error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.

I am new to angular 2 and promises/observables so I must be doing something obviously wrong

Upvotes: 2

Views: 3425

Answers (1)

user4676340
user4676340

Reputation:

Did you try using your IDE to autocomplete after calling an Observable ? ...

this.getObsData(info).toPromise();
this.anhttpservice(a,b,c).toPromise();

(Altough I recommend sticking to observables, but it's your choice)

Upvotes: 3

Related Questions