【发布时间】:2018-10-15 09:42:38
【问题描述】:
我有一个变量loggined,我使用logTog() 方法更改了它的值。在此方法中,我向传输当前结果to auth.guard 的服务发出请求。在控制台“未定义”为什么以及如何解决?
AppComponent代码:
export class AppComponent implements OnInit {
loggined: boolean = false;
constructor(private galleryService: GalleryService) {}
ngOnInit() {
this.logTog();
}
logTog(): void {
this.loggined = !this.loggined;
this.galleryService.auth(this.loggined);
}
}
服务:
auth(log:boolean):boolean {
console.log(log);
return log;
}
守卫:
export class AuthGuard implements CanActivate, OnInit {
constructor(private galleryService: GalleryService) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.galleryService.auth();
}
ngOnInit() {
}
}
【问题讨论】:
-
不相关,但您可能正在寻找
logged_in。在声明中赋值时也不需要设置类型。 -
在 guard 文件中,canActivate 函数应该返回 true 或 false。您正在从 canActivate 返回 this.galleryService.auth() 但您没有将任何参数传递给函数。
-
@nilansh 如何正确传递“guard”中变量“this.loggined”的值?
-
@IgorShvets 你可以在下面看到答案。
标签: javascript angular typescript authentication guard