HTTP错误处理程序中的Angular 2 router.navigate()

时间:2017-01-12 22:10:15

标签: angular angular2-routing

如果服务器返回401错误,我正在尝试使用angular导航到登录页面的系统,我尝试了这个,但它没有导航:

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable }     from 'rxjs/Observable';
import { Router } from '@angular/router';

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthService {

  private heroesUrl = 'http://localhost:8000/auth/loggedIn';

  constructor (private http: Http, private router: Router) {}

  loggedIn (): Observable<string|number> {
    return this.http.get(this.heroesUrl)
      .map(res => { return res.json(); })
      .catch(this.handleError);
  }

  private handleError (error: Response|any) {
    if (error.status == 401) {
      this.router.navigate(['/path_to_login_page']);
      return error.status;
    }
  }
}

我已经检查了服务器的响应,我也控制了登录的error.status == 401,它确实返回true,任何人都可以帮我解决这个问题。

提前致谢

2 个答案:

答案 0 :(得分:4)

Angular提供了两种导航选项(Router Class):

根据提供的命令数组和起点进行导航。如果没有提供起始路线,则导航是绝对的。用法:

this.router.navigate(['team', 33, 'user', 11], {relativeTo: route});

根据提供的网址导航。此导航始终是绝对的。用法:

this.router.navigateByUrl('/team/33/user/11');

如果您尝试使用第一个选项,请在命令前删除/

this.router.navigate(['path_to_login_page']);

答案 1 :(得分:1)

What I had to do was to incapsulate the this.router.navigate([]) inside an setTimeout(() => ...) function.

So this would like something like

private handleError (error: Response|any) {
    if (error.status == 401) {
      setTimeout(() => this.router.navigate(['/path_to_login_page']));
      return error.status;
    }
  }

I know that this particular question is answered before, I just put it out here in case others like me ends up here :)

相关问题