在弹出窗口中完成身份验证后,如何在角度组件中显示数据?

时间:2018-11-13 13:06:38

标签: angular

我必须通过GitLab进行角度认证。所以我在我的angular-app中创建了一个按钮。单击该按钮后,将调用该函数login(),这将打开一个弹出窗口。成功登录后,我获得了访问令牌,通过该令牌我将从GitLab获取数据。

  isLoggedIn = true;
  api: any;
  public test: any;
  accessToken: any;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private gitLabApi: GitLabApiService,
    private cd: ChangeDetectorRef
  ) {

  }

  ngOnInit() {
    this.accessToken = localStorage.getItem('access_token');
    if (this.accessToken) {
      this.apiRequest();
    } else {
      let fragMent = this.route.snapshot.fragment; // only update on component creation
      this.accessToken = fragMent.split('=')[1].split('&')[0];
      if (this.accessToken || this.accessToken) {
        localStorage.setItem('access_token', this.accessToken);
      }
      window.close();
      this.router.navigate(['manager']);
      this.apiRequest();
    }

  }
  logOut() {
    if (this.accessToken) {
      console.log(localStorage.removeItem('access_token'));
      this.isLoggedIn = false;
      this.router.navigate(['logginIn']);
    }

    this.sideBar.afterLogIn = false;
  }


  apiRequest() {
    this.gitLabApi.getProjectApi(this.accessToken).subscribe(
      apiData => {
        this.api = apiData;
        // console.log(this.api);
        this.cd.markForCheck();
        this.isLoggedIn = true;
      },
      error => console.log(error.message)
    );
    this.sideBar.getCommitDetail();
    this.sideBar.afterLogIn = true;
  }

  logIn() {
    //window.location.href = authUrl;
    window.open(authUrl, "pop Up", "width=250, height= 250 ")
  }

但是在ngOnInit中关闭弹出窗口后,它没有重定向到我的页面。 如果我使用window.open而不是window.location.href,那么它可以正常工作。现在如何使用window.open实现相同的功能?

2 个答案:

答案 0 :(得分:0)

您可以检查此ng-bootstrap

答案 1 :(得分:0)

问题是window.close正在关闭路由器然后尝试导航的窗口。登录窗口关闭后,您需要logIn方法来处理应用程序原始实例的路由逻辑。示例:

logIn() {
  const newwindow = window.open(authUrl, "pop Up", "width=250, height= 250 ");

  newwindow.onbeforeunload = () => {
    if (localStorage.getItem('access_token')) {
      this.router.navigate(['manager']);
      this.apiRequest();
    } else {
      // login failed
    }
  }
}