问题描述
我已经在Angular2中创建了一个Auth Manager来直接限制组件访问.我仍然对接触和学习概念还不陌生.
I have created a Auth Manager in Angular2 to restrict Component access directly .I am still new to angular and learning the concepts.
如果用户名不正确,我可以限制用户.但是我无法使用组件中canActivate方法返回的值在前端显示消息.
I was able to restrict the user if the user name is not correct.But i am not able to use the value returned by the canActivate Method in my component to display a message in my front end.
我的AuthManager类
My AuthManager class
import { Injectable } from '@angular/core';
import { CanActivate,Router,ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router';
@Injectable()
export class AuthManager implements CanActivate{
user = "user";
constructor(private router:Router){
}
canActivate(route:ActivatedRouteSnapshot,state:RouterStateSnapshot){
console.log("Comes Here");
if(this.user == "user"){
return true;
}else{
console.log("YOur are not authorized");
this.router.navigate(['/persons']);
return false;
}
}
}
我能够看到YOur在日志中未被授权,但是如何在组件中使用该值.
I am able to see YOur are not authorized in log but how to use the value in a component.
我的app.router.ts
My app.router.ts
{
path: 'persons/:id',
component: PersonDetailComponent,
canActivate:[AuthManager]
}
推荐答案
我对问题的理解是,如果身份验证失败,您想向用户显示某种错误消息.@PierreDuc是正确的.但是我对此有不同的看法.
What i understood by the Question is that you want to display Some kind of Error Message to the User if the Auth Fails.@PierreDuc is correct.But i have a different approach to this.
您可以做的就是创建一个服务类
what you can do is create a service class
authenticate.service.ts
import {Injectable} from '@angular/core'
@Injectable()
export class AuthenticateService
isAuthenticated(//take the user credentials here):boolean{
return true // if the credentials are correct
or retun false // if the credentials donot match.
}
在您的组件和AuthManager中使用此类
make use of this class in your component and AuthManager
import { Injectable } from '@angular/core';
import { CanActivate,Router,ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router';
import {AuthenticateService} from './authenticate.service'
@Injectable()
export class AuthManager implements CanActivate{
user = "user";
constructor(private router:Router,private authenticateService:AuthenticateService){
}
canActivate(route:ActivatedRouteSnapshot,state:RouterStateSnapshot){
console.log("Comes Here");
return this.authenticateService.isAuthenticated();
}
}
并在组件中检查相同
this.authenticateService.isAuthenticated()== false
*ngIf and then display an error message to the user.
希望这是您正在查看的内容.它不只是问题的答案,而是解决问题的一种方法.
Hope this is what you where looking at . it not exactly the answer of the question but a way to solve your problem.
这篇关于获取组件中Angular2 Route中canActivate方法返回的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!