1

At the lowest level, I have a service called AuthHttpService, which takes the request, attaches auth headers, and then calls the server.
Each component has its own data service, so if I had a StudentComponent, it would have a StudentService, which would call

getStudents(): Observable<Student[]> {
    return this._authHttpService.get('/Students')
         .map((response: Response) => <Student[]> response.json());
}

So in the component, I would call (for example)

this._studentService.getStudents().subscribe( data => { this.students = data} );

All of this works wonderfully, and has for months. **However, today I'm trying to implement a global redirect on a status of 401 **

How can I go about implementing this in my AuthHttpService?

In AuthHttpService, I tried replacing the return this.http.get(url, {headers: this.headers}) with

  this.http.get(environment.apiUrl + '' + url, {headers: this.headers}).subscribe(r => {
    if (r.status !== 401) {
      return r;
    } else  {
      this._router.navigateByUrl(loginUrl)
    }
  });

but now the .map in the component services is failing, because i'm no longer returning an observable, but instead I'm returning the actual response.

Alex Kibler
  • 4,674
  • 9
  • 44
  • 74

2 Answers2

0

If your component will get 401 in the subscribe() method, the response object won't contain an array of students. So try this:

this._studentService.getStudents().subscribe( data => { 
    if (Array.isArray(data)){
        this.students = data;
    } else {
      // check for the error and navigate to URL
    }

} );
Yakov Fain
  • 11,972
  • 5
  • 33
  • 38
0

To redirect on 401 all you have to do is .catch() it in your AuthHttpService on each of your HTTP calls like:

 get(url, params) {
    const headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.get(url, {
        headers: headers,
        search: params
    }).catch(err => {
        if (err.status === 401) {
            this.router.navigate(['/login');
            return Observable.throw('Unauthorized');
        }
    });
}

Inspired by this answer: https://stackoverflow.com/a/39878176/1742393

Community
  • 1
  • 1
rbj325
  • 954
  • 8
  • 17