![](/img/trans.png)
[英]angular 5 consoling http toPromise() request returns undefined
[英]Getting Post angular 2 toPromise HTTP
您好,我需要在發布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) => {
...
});
}
}
然后當我在主要組件中使用時
send(){
respondJSON = apistorage.rs();
console.log(respondJSON);
}
responseJSON未定義
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.