加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 在已解决的承诺中返回一个Observable

发布时间:2020-12-17 17:22:13 所属栏目:安全 来源:网络整理
导读:试图返回一个Observable. 我该怎么办呢? get(url) : Observableany { let headers = new Headers(); this.SetAuthorizationHeader(headers).then(() = { // Resolving a promise return this.http.get(url,{ // -- I need to return the Observable from he
试图返回一个Observable.
我该怎么办呢?

get(url) : Observable<any> {
    let headers = new Headers();
    this.SetAuthorizationHeader(headers).then(() => { // Resolving a promise
      return this.http.get(url,{ // <-- I need to return the Observable from here
          headers: headers
      });
    });
  }

消费(不工作):

public GetInfo() : Observable<any> {
    return this.authHttpClient.get(this.constants.api_base + "/users/info")
        .map((res: Response) => res.json());
}

谢谢!

解决方法

您只需要返回this.SetAuthorizationHeader(headers)方法,因此在解析SetAuthorizationHeader方法时,它将返回http.get调用observable.

Here you need to remove Observable<any> from get method return type,
as actually it is going to return Promise object.

get(url) : any {
    let headers = new Headers();
    //return promise here to continue chain & return inner observable.
    return this.SetAuthorizationHeader(headers).then(() => { // Resolving a promise
      return this.http.get(url,{ // <-- I need to return the Observable from here
          headers: headers
      });
    }).map(data => data.json());
}

消费

public GetInfo() : any { //here also it will be any,because you are returning `authHttpClient.get` at the end
    return this.authHttpClient.get(this.constants.api_base + "/users/info"));
}

获取信息消费

this.user.GetInfo().then(obs => 
    obs.subscribe(
      user => { alert(JSON.stringify(user)); },(error) => { alert(JSON.stringify(error)); }
);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读