在angular2中,我无法使CanDeactivate工作

时间:2016-11-05 11:50:32

标签: angular angular2-routing

在angular2中我试图让CanDeactivate工作。 我目前正在使用我的主页路线测试此功能。

结果我喜欢的是:如果用户未经过身份验证,则会将用户重定向到另一个页面。

我使用的是带有angular2的打字稿,我有最新的库和稳定的angular2应用程序。

我已尝试过以下尝试让它发挥作用。

我对归属路线档案的尝试:

     import { Route, CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HomeComponent } from './index';

export const HomeRoutes: Route[] = [
  {
    path: '',
    pathMatch: 'full',
    component: HomeComponent,
    canActivate: [CanDeactivateTeam]
  },
  {
    path: 'home',
    pathMatch: 'full',
    component: HomeComponent,
    canActivate: [CanDeactivateTeam]
  },
  {
    path: 'homepage',
    pathMatch: 'full',
    component: HomeComponent,
    canActivate: [CanDeactivateTeam]
  }
];

class UserToken {}

@Injectable()
class Permissions {
  canDeactivate(user: UserToken, id: string): boolean {
    return true;
  }
}

@Injectable()

class CanDeactivateTeam implements CanDeactivate<HomeComponent> {
  constructor(private permissions: Permissions, private currentUser: UserToken) {}
  canDeactivate(
    component: HomeComponent,
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean>|Promise<boolean>|boolean {
    return this.permissions.canDeactivate(this.currentUser, route.params.id);
  }
}

这是我的新错误:

  

未捕获(承诺):错误:必须定义令牌!

1 个答案:

答案 0 :(得分:1)

  • pathMatch: 'full'添加到空路径路径。错误消息是否有更多详细信息?

  • @Injectable()添加到Permissions

@Injectable()
class Permissions {
  canDeactivate(user: UserToken, id: string): boolean {
  • 确保您提供CanDeactivateTeamPermissionUserToken
@NgModule({
  imports: [...],
  providers: [CanDeactivateTeam, Permission, UserToken],
  ...
})
export class AppModule {}