"承诺"类型中不存在"订阅"属性

dr_*_*mio 9 javascript rxjs ionic3 angular

我仍然对rxjs如何工作感到困惑.

我正在构建一个Ionic应用程序,它向我的服务器发出请求并期望json.我已经成功订阅了http.post并获取了我需要的数据.

但是现在我的问题是我需要在我从Storage获得的http请求中传递一个auth令牌.这是一个问题,因为我需要等到存储准备就绪,然后在调用http.post请求之前从中获取我的令牌值.

这是我试图获取我的json数据的地方

getPlanograms() {

    //API URL
    let requestURL = 'https://myapiurlhere';
    let headers = new Headers({'Content-Type': 'application/json'});

    return this.storage.ready().then(() => {

        return this.storage.get('id_token').then((val) => {

            headers.append('Authorization', 'Bearer ' + this.authCredentials.token);
            let options = new RequestOptions({headers: headers});
            return this.http.post(requestURL, {}, options)
                .map(response => <Planogram[]>response.json());

        })
    });
}
Run Code Online (Sandbox Code Playgroud)

从这里开始调用

 ionViewDidLoad (){
    this.merchandisingDataService.getPlanograms()
        .subscribe(Planogram => this.planograms = Planogram);
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试这样做时,我得到以下错误

"承诺"类型中不存在"订阅"属性.

实现目标的最佳方式是什么?

0xc*_*aff 9

您可以.then()通过更改来消费:

ionViewDidLoad () {
    this.merchandisingDataService.getPlanograms()
        .then(Planogram => this.planograms = Planogram);
}
Run Code Online (Sandbox Code Playgroud)

或者,你可以getPlanograms退货Observable.

getPlanograms() {   

    // API URL
    let requestURL = 'https://myapiurlhere';
    let headers = new Headers({'Content-Type': 'application/json'});

    // this converts from promise to observable
    return Observable.fromPromise(this.storage.ready()
        .then(() => this.storage.get('id_token'))
        .then((val) => {
            headers.append('Authorization', 'Bearer ' + this.authCredentials.token);
            let options = new RequestOptions({headers: headers});

            return this.http.post(requestURL, {}, options)

                // map converts from observable to promise
                // (returned by response.json())
                .map(response => <Planogram[]>response.json());
        });
    }));
}
Run Code Online (Sandbox Code Playgroud)

现在你可以.subscribe()像在问题中一样消费.


dr_*_*mio 2

根据 caffatedmonkey 的建议,我最终得到了这个工作函数:

    getPlanograms() {

    //API URL
    let requestURL = 'https://myapiurlhere';

    return Observable
        .fromPromise(this.storage.get('id_token'))
        .flatMap(token =>{
            let headers = new Headers({'Content-Type': 'application/json'});
            headers.append('Authorization', 'Bearer ' + token);
            let options = new RequestOptions({headers: headers});
            return this.http.get(requestURL, options)
                .map(response => <Planogram[]>response.json())
                .catch(this.handleError);
        }
    );
}
Run Code Online (Sandbox Code Playgroud)