Angular 2 redirect in http/rxjs catch callback cau

2020-04-16 18:16发布

问题:

When redirecting from the rxjs catch function I get the error: EXCEPTION: TypeError: Cannot read property 'subscribe' of undefined

Here's the relevant part of 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)
  }
}

In the consuming component:

...
ngOnInit(){
  this.getContacts()
}

getContacts(){
  this.contactService.getContacts().subscribe(
    (contacts) => { this.contacts = contacts },
    (error) => { this.errorMessage = error }
  )
}

This question (Angular 2. How to handle 4xx errors with redirect in Observable?) would suggest that I'm doing this right, but maybe I'm missing something in my component?

回答1:

There is a return missing

return this.handleError(err)