对不起,我的问题很傻。
我尝试在服务中实现行为主体,然后从登录组件中调用它。
这是我的服务
private currentTokenSubject: BehaviorSubject<AuthResponse>;
public currentToken: Observable<AuthResponse>;
constructor(private httpClient: HttpClient) {
this.currentTokenSubject = new BehaviorSubject<any>(localStorage.getItem(TOKEN_NAME));
this.currentToken = this.currentTokenSubject.asObservable();
}
public get currentTokenValue(): AuthResponse {
// console.log('auth service: ' + this.currentTokenSubject.value)
return this.currentTokenSubject.value;
}
login(usernameOrEmail:string, password: string){
return this.httpClient.post<any>(this._loginUrl,{usernameOrEmail, password})
.pipe(map(res => {
//login sucess if there's jwt token in the response
if(res && res.accessToken){
//store user details and jwt token in local storage to keep user logged in between page refresh
localStorage.setItem(TOKEN_NAME, res.accessToken);
this.currentTokenSubject.next(res.accessToken);
console.log(this.currentTokenValue); // It's changed
}
return res;
}));
}
此处是我组件中的代码
constructor(
private formBuilder: FormBuilder,
private authService: AuthService,
private router: Router,
private route: ActivatedRoute,
private alertService: AlertService
) {
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '';
if(this.authService.currentTokenValue){
this.router.navigate([this.returnUrl]);
}
}
onSubmit(): void{
for (const i in this.loginForm.controls) {
this.loginForm.controls[i].markAsDirty();
this.loginForm.controls[i].updateValueAndValidity();
}
// stop here if form is invalid
if (this.loginForm.invalid) {
return;
}
const val = this.loginForm.value;
this.isLoading = true;
this.authService.login(val.username, val.password) // calls the service
.pipe(first())
.subscribe(
data => {
setTimeout(() => {this.router.navigate([this.returnUrl])},500);
},
error => {
this.alertService.error(error);
this.isLoading = false;
}
);
}
这是守卫
constructor(
private router: Router,
private authService: AuthService
){}
canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot
) {
const currentToken = this.authService.currentTokenValue;
console.log(currentToken); // return null
if(currentToken){
//authorized
return true;
}
// not logged in : redirect to login page with return url
//console.log(state.url)
this.router.navigate(['login'], { queryParams : { returnUrl: state.url }});
return false;
}
当我尝试登录console.log时,警卫返回null。
任何人都可以向我解释,为什么会这样?
更新
应用程序没有问题,您必须做的是:
仅一次使用提供商
将服务导入到app.module.ts中的@ngmodule,否则将为每个组件/模块创建实例。
答案 0 :(得分:0)
如果要读取当前值而不是。.getValue()
value
。
public get currentTokenValue(): AuthResponse {
return this.currentTokenSubject.getValue();
}
答案 1 :(得分:0)
更新
应用程序没有问题,您必须做的是:
仅一次使用供应商
将服务导入到app.module.ts中的@ngmodule,否则将为每个组件/模块创建实例。