[英]Angular - router.navigate() not redirecting to target page
我正在一個簡單的登錄過程中,除非經過身份驗證,否則我將嘗試保護某些路徑。
app.routing.ts
const appRoutes: Routes = [
{
path: 'add-merchant-admin',
component : AddMerchantAdminComponent,
canActivate : [AuthGard]
},
{
path: 'list-merchant-admin',
component : ListMerchantAdminComponent,
canActivate : [AuthGard]
},
{
path: 'login',
component : LoginComponent
},
{
path: '**',
component: NotFoundComponent
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
authGard.service.ts
import { Injectable } from '@angular/core';
import {CanActivate, Router} from "@angular/router";
import {AuthenticationService} from "../authentication-service/authentication.service";
@Injectable()
export class AuthGard implements CanActivate {
constructor(private _authService:AuthenticationService, private _router:Router) { }
canActivate() {
if(this._authService.isLoggedIn)
return true;
this._router.navigate(['login']);
return false;
}
}
認證服務
@Injectable()
export class AuthenticationService {
isLoggedIn = false;
constructor() {
}
login(){
this.isLoggedIn = true;
}
logout(){
this.isLoggedIn = false;
}
}
當我嘗試訪問諸如add-merchant-admin之類的受保護路徑時 ,瀏覽器會繼續加載該頁面,並占用大量內存,直到凍結為止。
這些是有關我的應用程序的詳細信息。
節點:6.10.2
操作系統:win32 x64
@角度/動畫:4.2.3
@ angular / common:4.2.3
@角度/編譯器:4.2.3
@角/核心:4.2.3
@角度/形式:4.2.3
@角度/ http:4.2.3
@角度/材質:2.0.0-beta.6
@角度/平台瀏覽器:4.2.3
@ angular / platform-browser-dynamic:4.2.3
@角度/路由器:4.2.3
@角度/ cli:1.0.1
@ angular / compiler-cli:4.2.3
依賴注入已驗證。
組件已正確導入。
我不知道此應用程序是怎么回事,通常它應該可以工作。
希望你們能幫助我。
非常感謝。
如下修改路由,
const appRoutes: Routes = [
{
path: 'add-merchant-admin',
component : AddMerchantAdminComponent,
canActivate : [AuthGard]
},
{
path: 'list-merchant-admin',
component : ListMerchantAdminComponent,
canActivate : [AuthGard]
},
{
path: 'login',
component : LoginComponent
},
{
path: 'notfound',
component :NotFoundComponent
},
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: '**',
redirectTo: 'notfound',
pathMatch: 'full'
},
];
將AuthGuard更改為此:
import { Injectable } from '@angular/core';
import {CanActivate, Router} from "@angular/router";
import {AuthenticationService} from "../authentication-service/authentication.service";
@Injectable()
export class AuthGard implements CanActivate {
constructor(private _authService:AuthenticationService, private _router:Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if(this._authService.isLoggedIn)
return true;
this._router.navigate(['/login']);
return false;
}
}
在導航方法的參數數組的第一個參數中,使用/
作為前綴,您可以告訴angular路徑是絕對的(從根開始)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.