将Angle 2发布到Promise HTTP

Jęd*_*ski 2 javascript json http angular

您好,我需要在发布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) => {
            ...
                });
    }
}
Run Code Online (Sandbox Code Playgroud)

然后当我在主要组件中使用时

send(){
    respondJSON = apistorage.rs();
    console.log(respondJSON);
    }
Run Code Online (Sandbox Code Playgroud)

responseJSON未定义

Hin*_*ich 5

respond 在代码中将始终是undefined,因为您正在异步调用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);
    }
}
Run Code Online (Sandbox Code Playgroud)