在angular 2中,如何在401的自定义Auth HTTP服务中重定向



在最底层,我有一个名为AuthHttpService的服务,它接受请求,附加认证头,然后调用服务器。
每个组件都有自己的数据服务,所以如果我有一个StudentComponent,它就会有一个StudentService,它会调用

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

在组件中,我将调用(例如)

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

所有这些都非常有效,并且已经持续了几个月。**然而,今天我试图实现一个全局重定向状态401 **

我如何在我的AuthHttpService中实现这一点?

在AuthHttpService中,我尝试用

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

但是现在组件服务中的.map失败了,因为我不再返回一个可观察对象,而是返回实际的响应。

如果组件将在subscribe()方法中获得401,则响应对象将不包含学生数组。所以试试这个:

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

要在401上重定向,你所要做的就是在每个HTTP调用的AuthHttpService中。catch()它,如:

 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');
        }
    });
}

受此答案启发:https://stackoverflow.com/a/39878176/1742393

最新更新