【问题标题】:Using promise with observable in ionic 2 applications在 ionic 2 应用程序中使用带有 observable 的 promise
【发布时间】:2026-01-13 14:35:01
【问题描述】:

我试图在 ionic 2 应用程序中调用 Web 服务,但在 promise 和 observable 之间陷入了困境。 这是我在单击按钮时调用的函数-

getUserDetailsIfAccessTokenIsSuccess()


{
    this.remedyService.userGetDetail(this.loginDetailsObj.username).subscribe(
      data =>{
        console.log("userGetDetail Success="+JSON.stringify(data));
      },
      err =>{
        console.log("userGetDetail Success="+JSON.stringify(error));
        },
       () =>{
              console.log("Get Userdetails Completed");
      });
}

现在我在我的服务文件中调用 userGetDetail 函数。

userGetDetail(eid){
    var url = '/userGetDetail';
    var params = {
                'EID':eid
            };
    console.log(JSON.stringify(params));
    var headers = new Headers();
    this.createAuthorizationHeader(headers);
    this.storage.get('remedyAccessToken').then((value)=>{
        var token  = value.toString();
        console.log("TOKEN IN REMEDYSERVICES="+token);
        headers.append('Authorization', token);
        console.log("header value inside="+JSON.stringify(headers));
    })
    console.log("header value outside="+JSON.stringify(headers));
    let options = new RequestOptions({ headers: headers });
    this.response = this.http.post(url,this.urlEncode(params),options).map(res => res.json());
    console.log("Response JSON="+JSON.stringify(this.response));
    return this.response;
}

现在的问题是,在将授权附加​​到标题之前,流程将转到下一行,并且 web api 给出了错误。 无论如何,我可以以这样的方式进行同步,即在附加授权之后,只会发生服务调用。 我尝试将 web api 调用放入 then 块中,但它将服务调用作为一个承诺。 任何帮助将不胜感激。

【问题讨论】:

    标签: angular ionic-framework ionic2 angular2-http


    【解决方案1】:

    您需要访问 storage.get 内的 api 。这确保在您进行 api 调用时值可用。然后将api 调用(即Observable)转换为toPromise() 的promise。现在您可以以 Promise 的身份访问响应。这是您的代码中的大致工作流程。

    this.storage.get('remedyAccessToken').then((value)=>{
        var token  = value.toString();
        console.log("TOKEN IN REMEDYSERVICES="+token);
        headers.append('Authorization', token);
        console.log("header value inside="+JSON.stringify(headers));
        console.log("header value outside="+JSON.stringify(headers));
       let options = new RequestOptions({ headers: headers });
       this.response = this.http.post(url,this.urlEncode(params),options).map(res => res.json());
       console.log("Response JSON="+JSON.stringify(this.response));
       return this.response.toPromise();
    })
    
    
    
    this.remedyService.userGetDetail(this.loginDetailsObj.username).then(fn).catch(fn);
    

    或者,如果您希望输出为 Observable,请遵循此方法。

    Observable.fromPromise(this.storage.get('remedyAccessToken')).flatMap((value)=>{
            var token  = value.toString();
            console.log("TOKEN IN REMEDYSERVICES="+token);
            headers.append('Authorization', token);
            console.log("header value inside="+JSON.stringify(headers));
            console.log("header value outside="+JSON.stringify(headers));
           let options = new RequestOptions({ headers: headers });
           this.response = this.http.post(url,this.urlEncode(params),options).map(res => res.json());
           console.log("Response JSON="+JSON.stringify(this.response));
           return this.response
    })
    

    这种方法可以达到你想要的结果。

    【讨论】:

    • 嗨 Raj,无论如何我可以将返回 this.response 转换为观察者吗?
    • HI Raj,我猜 flatMap 不是 promise 的属性,我的存储正在返回 promise,所以 flatMap 不能在这里使用。
    • 抱歉,我的回答中缺少括号。我已经更新了它。 flatMap 作用于 Observable。您可能需要导入它。 import 'rxjs/add/operator/flatMap'.
    • 谢谢,我得到了解决方案。感谢您的帮助,祝您新年快乐。
    • @RHUL 如果有帮助,请将其标记为答案
    【解决方案2】:

    在 Promise 中调用观察者并返回观察者的正确方法是这样的-

    return Observable.fromPromise(this.storage.get('remedyAccessToken')).then((value)=>{
        var token  = value.toString();
        console.log("TOKEN IN REMEDYSERVICES="+token);
        headers.append('Authorization', token);
        console.log("header value inside="+JSON.stringify(headers));
        console.log("header value outside="+JSON.stringify(headers));
       let options = new RequestOptions({ headers: headers });
       this.response = this.http.post(url,this.urlEncode(params),options).map(res => res.json());
       console.log("Response JSON="+JSON.stringify(this.response));
       return this.response.toPromise();
    })
    

    【讨论】:

    • 我在 Observable 上看不到 get 运算符。 reactivex.io/documentation/operators.html
    • 更新到 then 的 promise 方法...这是一个错误
    • 解决方案中多了一个括号。并标记一个答案,以便对其他人有所帮助。