从rxjs catch函数重定向时,出现错误:EXCEPTION:TypeError:无法读取未定义的属性“ subscribe”
这是contactService的相关部分:
getContacts () {
...
return this.http.get(this.apiUrl, options)
.map(this.extractData, this)
.catch(err => {
this.handleError(err)
})
}
...
handleError (error) {
if(error.status === 401){
//the redirect works great, except, when added, I get the exception error
this.router.navigate(['/login'])
return Observable.of([])//this is my attempt based on link below
}
else{
// In a real world app, we might send the error to remote logging infrastructure
let errMsg = error.message || 'Server error'
console.error(errMsg) // log to console instead
return Observable.throw(errMsg)
}
}
在使用组件中:
...
ngOnInit(){
this.getContacts()
}
getContacts(){
this.contactService.getContacts().subscribe(
(contacts) => { this.contacts = contacts },
(error) => { this.errorMessage = error }
)
}
这个问题(Angular 2. How to handle 4xx errors with redirect in Observable?)表明我做对了,但是也许我的组件中缺少某些东西?
解决方法:
缺少回报
return this.handleError(err)