【问题标题】:Angular2 Jsonp call with promise带有承诺的Angular2 Jsonp调用
【发布时间】:2015-11-12 16:01:49
【问题描述】:

目前我正在研究 Angular2-alpha45。

由于 CORS 问题,我必须进行 JSONP 调用。问题是,通话需要一些时间,我不知道如何将答案包装成承诺。

我可以将常规的 http.get 包装到 Promise 中,但是由于 CORS,这不是我需要的解决方案。

工作 http.get 示例:

import {Jsonp, Http} from 'angular2/http';

// works
this.getPromise().then(result => {
    console.dir(result)
});

getPromise(): Promise<Array> {
    return this.http
    .get('test.json')
    .map((res) => {
        return res.json()
    })
    .toPromise();
}

Jsonp 不工作:

import {Jsonp, Http} from 'angular2/http';

// Doesn't work
this.getPromiseJsonp().then(result => {
    console.dir(result)
});

getPromiseJsonp(): Promise<Array> {
    // this.generateJsonpUrlDataGet2 generates the URL for call, URL is correct
    // response is sent but without a promise
    var url = this.generateJsonpUrlDataGet2('SingleUser', "test", '');
    return this.jsonp.request(url).subscribe(res => {
        // console.dir() get called!
        console.dir(res._body);
        return res._body;
    }).toPromise();
}

谁能告诉我如何将 Jsonp 调用封装到一个 Promise 中?

【问题讨论】:

  • 为什么需要 Promise? Observable 也可以工作,无论请求需要多长时间。无论如何,要回答您的问题,您应该发送至this.jsonp.request(url).toPromise().then(() =&gt; ...),尽管您使用subscribe 所做的完全相同。

标签: angular es6-promise


【解决方案1】:

以下是如何使用 Promise 进行 JSONP-Call。我只是拿错了函数,看起来必须映射 Promise,所以必须调用 map() 函数:

return this.jsonp.request(url).map(res => {
    return res.json();
}).toPromise();

【讨论】:

    猜你喜欢
    • 2016-07-25
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    相关资源
    最近更新 更多