bbb(){
return new Promise((resolve, reject) => {
this.http.get(this.url).subscribe(data => {
resolve(data)
},
error => {
reject(error);
},
);
});
}
ngAfterContentInit(){
console.log(//THIS LINE
this.bbb().then(son => {
return son;
}));
}
-此行-在控制台中返回ZoneAwarePromise。我如何退还儿子的价值?
答案 0 :(得分:1)
更好的做法是使用Observable
:
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
bbb() {
return this.http.get(this.url)
.pipe(
catchError(err => {
console.log('err', err);
return throwError('Something bad happened; please try again later.');
});
}
然后,只需订阅bbb
:
import { Subscription } from 'rxjs';
testSubscription: Subscription;
ngAfterContentInit() {
this.testSubscription = this.bbb()
.subscribe(son => {
console.log('son', son); // here you get the result
});
}
别忘了unsubscribe
:
ngOnDestroy() {
this.testSubscription.unsubscribe();
}
如果您仍然想使用Promise
:
bbb() {
return this.http.get(this.url).toPromise();
}
要获取bbb
的结果:
ngAfterContentInit() {
this.bbb()
.then(son => {
console.log('son', son); // here you get the result
})
.catch(err => {
console.log(err);
});
}