简体   繁体   English

将Angle 2发布到Promise HTTP

[英]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: 您好,我需要在发布json对象后使用toPromise获得一些响应,它是我的代码,响应未定义:

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 responseJSON未定义

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. respond总是会在你的代码是不确定的,因为你正在为一个Web服务的异步调用,你不登录到控制台之前等待。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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