简体   繁体   中英

Getting Post angular 2 toPromise HTTP

Hello I need to get some response after posting json object, using toPromise, its my code, respond is undefined:

export class ApiStorage{
constructor( @Inject(Http) private http: Http ){}
    rs(){
    this.http.post('http://0.0.0.0:80/student/outbound', this.json, headers)
            .toPromise()
            .then(response => {
                respond = JSON.stringify(response);
                return respond; //<- edited
            })
            .catch((error: any) => {
            ...
                });
    }
}

then when in main component I use

send(){
    respondJSON = apistorage.rs();
    console.log(respondJSON);
    }

respondJSON is undefined

respond will always be undefined in your code, because you are making an asynchronous call to a webservice, which you do not await before logging to console.

export class ApiStorage{

    constructor( @Inject(Http) private http: Http ){}

    rs() {

        return this.http.post('http://0.0.0.0:80/student/outbound', this.json, headers)
            .toPromise()
            .then(response => {
                let respond = JSON.stringify(response));
                return respond;
            })
            .catch((error: any) => {
                ...
            });
    }
}

// rs now returns a promise, which can be used like this
// inside another function
send() {
    apistorage.rs().then(res => {
        console.log(res);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM