[英]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.