Angular2:使用AuthGuard路由重定向

时间:2017-01-24 11:20:31

标签: angular routing angular-routing

我有一个Angular2应用程序,如果用户没有登录,应阻止到某个页面的路由。这是我的app.routes文件

export const routes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'login', component: LoginComponent },
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
  { path: '**', component: LoginComponent },
];

和我的AuthGuard文件

@Injectable()
export class AuthGuard implements CanActivate {
response: ResponseInterface;

constructor(private router: Router, private localStorage: LocalStorageService,
 private services: MyService) { }
canActivate() {

let token = String(this.localStorage.get('token'));
if (token != null) {
  this.services.keepAlive(token).subscribe(
    response => this.response = response,
    error => alert(error),
    () => {
      if (this.response.status == 'OK') {
        console.log("response OK");
        return true;
      } else {
        console.log("response KO");
        this.router.navigate(['/login']);
        return false;
      }
    }
  )

} else {
  this.router.navigate(['/login']);
  return false;
}

现在,如果我尝试导航到http://localhost:4200/#/home路径并且我已经将令牌存储到localStorage中,则不会发生任何事情:主页未显示且导航栏上的路径变为http://localhost:4200/#/。 怎么了?

1 个答案:

答案 0 :(得分:5)

<?php $String = "Local@agent:900/n"; echo $String; echo '<br>'; $new_string = str_replace('/n', '', $String); echo $new_string; 方法应返回canActiveObservable<boolean>Promise<boolean>

您正在订阅boolean Observable,并将this.services.keepAlive值返回到订阅回调,而不是将其返回到boolean方法。更改您的代码如下:

canActivate

这样,布尔类型(canActivate(): Observable<boolean> | Promise<boolean> | boolean { let token = String(this.localStorage.get('token')); if (token != null) { return this.services.keepAlive(token) .map(response => { if (response.status == 'OK') { console.log("response OK"); return true; } else { console.log("response KO"); this.router.navigate(['login']); return false; } }); } else { this.router.navigate(['login']); return false; } } )的Observable将返回到Observable<boolean>方法,路由解析应该按预期工作。