Angular2 Jsonp call with promise

2019-07-19 02:30发布

问题:

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