I am trying to return an observable after a successful completion of my Promise, but that function is not returning Observable. To be specific to code, i want to fetch auth token from storage (returns promise) and after that data got fetched then generate a Post request to Api (returns Observable). By doing so, sublime text gives an error on function that "a function whose declared type is neither 'void' nor 'any' must return a value" below is my code,
logout() : Observable<any>{ this.userData.getAuthToken().then((token)=>{ this.token = token; this.headers = new Headers ({ "X-USER-TOKEN": token }); this.options = new RequestOptions ({ headers: this.headers }); var logout_url = "Api logout method"; return this.http.post(logout_url,{},this.options) .map (res => res.json()) }); }
if i simply do a post request then it returns fine like this
return this.http.post(logout_url,{},this.options) .map (res => res.json())
but when i try to fetch data it do not return value from this post request. Any help will be much Appreciated! Thanks in advance
How to Convert an Observable to a Promise in Angular? Since the get method of HttpClient returns an observable, we use the toPromise() method to convert the observable to a promise. Since you can convert an observable to a promise, you can make use of the async/await syntax in your Angular code.
The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.
The Promise simply represents some future value. It does not represent the operation which generates the value. You cannot cancel a value.
Use fromPromise
to convert the promise into an observable and use mergeMap
to emit the HTTP response into the composed observable:
import { Observable } from 'rxjs/Observable/'; import 'rxjs/add/observable/fromPromise'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/mergeMap'; logout(): Observable<any>{ return Observable.fromPromise(this.userData.getAuthToken()).mergeMap(token => { this.token = token; this.headers = new Headers({ "X-USER-TOKEN": token }); this.options = new RequestOptions({ headers: this.headers }); var logout_url = "Api logout method"; return this.http.post(logout_url, {}, this.options).map(res => res.json()); }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With