Angular2 Jsonp is calling with a promise

I am currently watching Angular2 -alpha45.

Due to the 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 in a promise.

I can transfer regular http.get to a promise, but due to CORS, this is not a solution for my needs.

Working example 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 does not work:

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 someone tell me how to wrap a Jsonp call in a promise?

+2
source share
1 answer

Here's how to make a JSONP-Call with a promise. I just took the wrong function, it looks like Promises, I need to display it, so I need to call the map () function:

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

Source: https://habr.com/ru/post/1627509/


All Articles