2017-07-05 36 views
2

你好,我需要得到张贴JSON对象,使用toPromise,其我的代码后,一些响应,响应未定义:获取后角2 toPromise HTTP

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) => { 
      ... 
       }); 
    } 
} 

那么当在主要成分我用

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

respondJSON是不确定的

+1

的[我如何返回从一个异步调用的响应?(可能的复制https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an - 异步呼叫) – echonax

回答

4

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

它的工作原理,谢谢:) –

+0

但你能再次帮助我,并告诉如何回复?当我使用respond = JSON.stringify(response)); 返回响应; // < - 这不会返回任何内容 –

+0

您可以为此发布一个新问题并显示更多代码,以便我们可以看到上下文吗?会更容易帮助。 – Hinrich