用户登录后重定向至受保护的路由不起作用-Angular应用

问题描述 投票:0回答:1

我一直在学习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

angular angular-ui-router
1个回答
1
投票

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

您的身份验证服务登录方法需要返回已经存在的方法的结果。这可能是一个应许或可观察的。这将使登录组件知道登录响应何时返回并且行为适当。

如果登录响应成功,那么您需要导航到合适的页面。在这种情况下,它要么是您当前在服务中获得的返回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);
      });
  }
}

auth服务

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());
}
© www.soinside.com 2019 - 2024. All rights reserved.