在 Ionic 2/Angular 2 中解决一些 Promise 之后如何返回 Observable? [英] How to return Observable after some Promise get resolved in Ionic 2/Angular 2?

查看:21
本文介绍了在 Ionic 2/Angular 2 中解决一些 Promise 之后如何返回 Observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在成功完成我的 Promise 后返回一个 observable,但该函数没有返回 Observable.具体到代码,我想从存储中获取身份验证令牌(返回承诺),然后在获取数据后生成对 Api 的 Post 请求(返回 Observable).通过这样做,sublime text 会在函数上给出一个错误,即声明类型既不是‘void’也不是‘any’的函数必须返回一个值"下面是我的代码,

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

推荐答案

使用 fromPromise 将 promise 转换为 observable 并使用 mergeMap 将 HTTP 响应发送到组合的 observable 中:

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

这篇关于在 Ionic 2/Angular 2 中解决一些 Promise 之后如何返回 Observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆