用户登录后重定向到受保护的路由,它不起作用 - Angular 应用程序



我一直在遵循 Angular 教程,到目前为止我能够让它工作,但我的应用程序在登录任何启用了"canActivate [AuthGuard]"选项的页面后不会重定向用户,我什至尝试在登录后单击任何"canActivate [AuthGuard]",它不会更改任何内容,而不是 URL, 不是页面,如果我使用"canActivate [AuthGuard]",我可以通过下拉菜单和所有内容导航到它。

请帮我找到问题。

到目前为止,我将我的项目上传到我的github配置文件中,以便您可以查看代码,与此功能相关的文件是"app.module.ts","app.component.ts","auth-guard.service.ts"和"auth.service.ts"。

https://github.com/jsalcedoa/oShop

登录后它不会重定向,因为您没有告诉它。

您的身份验证服务登录方法需要返回其中已有方法的结果。这可能是一个承诺或一个可观察的。这将允许登录组件知道登录响应何时返回并正常运行。

如果登录响应成功,则需要导航到合适的页面。在这种情况下,它要么是您当前在服务中获取的返回 URL,要么是您选择的路由。

登录组件

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
constructor(private auth: AuthService,
// inject Router and ActivatedRoute into components, not services
private route: ActivatedRoute,
private router: Router) { 
}
login() {
// assuming promise will be returned from auth service
// TODO: handle errors and display login error - out of scope for this question
this.auth.login()
.then(message => {
// moved from auth service
const returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '/';
// now do the navigation
this.router.navigateByUrl(returnUrl);
});
}
}

身份验证服务

login(): Promise<string> {
// I'm assuming that this is a promise that returns a message 
// for the purposes of demonstrating the general login pattern.
return this.afAuth.auth.signInWithRedirect(new auth.GoogleAuthProvider());
}

最新更新