簡體   English   中英

Angular 2 CanActivate被調用兩次

[英]Angular 2 CanActivate is called twice

我遇到了使用Angular的路線防護問題。

導航到不允許的頁面時,我的CanActivate防護被調用兩次,因為我沒有登錄。

我有1個根模塊,並提供了我的CanActivate后衛和其他服務。

先感謝您!

這是我的路由器:

const appRoutes: Routes = [
    {
        path: "",            
        pathMatch: "full",
        redirectTo: "/meal-list",
    },
    {
        path: "login",
        component: LoginComponent,
    },
    {
        path: "meal-list",
        component: MealListComponent,
        canActivate: [AuthActivateGuard],
    }  
];


export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true});

守衛:

@Injectable()
export class AuthActivateGuard implements CanActivate {


  constructor(private authService: AuthService,
              private router: Router) {
    console.log("guard created");
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|boolean {
    if (!this.authService.authenticated) {
      return this.authService.checkLogged().map(res => {
        this.authService.authenticated = true;
        return true;
      }).catch(()=> {
        this.authService.authenticated = false;
        this.router.navigate(["login"]);            
        return Observable.of(false);
      });
    }
    return true;
  }
}

雖然這不是一個解決方案,但它是一個答案:

使用散列路由時會發生這種情況(useHash:true)。

它可能是Angular路由器中的一個錯誤。

我還在調查是否有解決方案。

史蒂夫

我注意到它不適用於Hash:下面是我的示例,並注意:下面的代碼將調用penModalDialogInvalid()兩次,因為我使用

providers: [{provide:LocationStrategy,useClass:HashLocationStrategy}],



   @Injectable()
export class UserDetailsGuard implements CanActivate {


constructor(private _router:Router,
    private winRef: WindowRef){}

 canActivate(route:ActivatedRouteSnapshot,state: RouterStateSnapshot ) : boolean {

    let id=+route.url[0].path;

    if (isNaN(id) || id <1 ){
        this.winRef.nativeWindow.openModalDialogInvalid();
        //this._router.navigate(['/pagenotfound']);
        return false;
    }
    return true;

} 

}

如果我注釋掉上面的導航線,它將調用該函數一次!!!! 否則兩次,除了在Firefox和所有基於Firefox的瀏覽器!!!! 為什么???? 我不知道!!!!!

請在路由鏈接之前重新刪除斜杠。

redirectTo: "meal-list"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM