Angular2 JSONP调用与承诺 [英] Angular2 Jsonp call with promise

查看:143
本文介绍了Angular2 JSONP调用与承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在寻找进入Angular2-alpha45。

At the moment I'm looking into Angular2-alpha45.

在一个CORS-问题的原因我必须做出一个JSONP呼叫。问题是,该呼叫需要一些时间,我不知道如何回答包装成一个承诺。

In cause of a CORS-Problem I have to make a JSONP-Call. The problem is, that the call takes some time and i don't know how to wrap the answer into a promise.

我可以换一个普通http.get成一个承诺,但由于CORS的,这不是我需要的解决方案。

I can wrap a regular http.get into a promise, but because of CORS this isn't a solution for my needs.

工作http.get例如:

Working http.get example:

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:

Not Working 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调用到一个承诺?

Can anyone tell me how to wrap a Jsonp call into a promise?

推荐答案

下面是如何使一个承诺一个JSONP表决。我只是把错误的函数,看起来像承诺必须映射,因此地图() - 函数被调用:

Here is how to make a JSONP-Call with a Promise. I just took the wrong function, looks like Promises have to be mapped, so the map()-function has to be called:

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

这篇关于Angular2 JSONP调用与承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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