Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

ionic2 - How to return Observable after some Promise get resolved in Ionic 2/Angular 2?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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());
  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...