Angular2 Jsonp call with promise

浪子不回头ぞ 提交于 2020-01-24 12:42:04

问题


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

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.

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

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();
}

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();
}

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


回答1:


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();


来源:https://stackoverflow.com/questions/33675842/angular2-jsonp-call-with-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!