3

I have a code to get request. It's compiling and working but I have an error in console.

public get<T>(url: string, headers: Headers = this.jsonHeaders()): Observable<T> {
        return this._http.get(url, { headers: headers })
                   .catch((err: Response, caught: Observable<T>) => {
                       if (err.status === 401) {
                           this._router.navigate(["/auth/login"]);
                           return Observable.throw("401 Unauthorized");
                       }
                       return caught;
                   })
                   .map(res => <T>this.toJSON(res));
    }

error:

error TS2345: Argument of type '(err: Response, caught: Observable<T>) => ErrorObservable | Observable<T>' is not assignable to parameter of type '(err: any, caught: Observable<Response>) => Observable<any>'.
  Types of parameters 'caught' and 'caught' are incompatible.
    Type 'Observable<Response>' is not assignable to type 'Observable<T>'.
      Type 'Response' is not assignable to type 'T'.

I tried cast it to but it's not helped

1

1 Answer 1

9

You use the following:

.catch((err: Response, caught: Observable<T>) => {
  if (err.status === 401) {
    this._router.navigate(["/auth/login"]);
    return Observable.throw("401 Unauthorized");
  }
  return Observable.throw(caught); // <-----
})
Sign up to request clarification or add additional context in comments.

7 Comments

That is work fine but I still have an error in console.
Could you try: return caught.source;?
I think reason is that expected Observable<any> but return ErrorObservable
Yes agreed but the source property of the ErrorObservable contains the source observable of type Observable<any>. So it should fix the problem ;-)
But it's not =( Maybe because caught hasn't source property
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.