2016-11-24 86 views
1

我一直在嘗試實施Google身份驗證。Angular 2:Google身份驗證登錄工作只有一次

當localhost:4200第一次加載時,事情對我來說工作正常。

我可以瀏覽註冊和登錄之前通過谷歌按鈕登錄。

工作:現在,當我點擊谷歌登錄按鈕,它工作正常,我。我正在提出一個將導航欄更改爲登錄狀態的事件。 我甚至可以註銷。在註銷時,我再次提出了一個事件,將導航欄的 更改爲註冊,並重定向到登錄。

注意:請先閱讀工作。

不工作:註銷後我現在再次進入登錄屏幕。現在 當我再次單擊Google登錄按鈕時,onsuccess或方法不是調用 ,甚至調試並安慰它,沒有任何顯示。 on GoogleLoginSuccess方法不會再被調用?現在

當我再次刷新登錄頁面,我被重定向到家裏 頁作爲onGoogleLoginSuccess方法被調用,它廣播 事件很好地工作。

谷歌按鈕渲染 gInit我叫n個

ngAfterViewInit() { 
    this.gInit(); 
} 

gInit() { 

    var loginProxy = $.proxy(this.onGoogleLoginSuccess, this); 

    gapi.signin2.render(
    this.googleLoginButtonId, 
    { 
    "onSuccess": this.onGoogleLoginSuccess, 
    "scope": "profile", 
    "theme": "dark" 
    }); 
} 

在登錄成功

onGoogleLoginSuccess = (loggedInUser) => { 
    this._zone.run(() => { 
     console.log(this); 
     this.brodcastSignIn(); 
    });  
} 

唯一的錯誤跟蹤,因爲我不能夠調試或註銷在控制檯中,因爲方法未被調用。

I receive an error when logout redirects me to the login page. 

cb=gapi.loaded_0:266 Uncaught TypeError: Cannot read property 'style' of null(…) 
G_ @ cb=gapi.loaded_0:266 
(anonymous function) @ cb=gapi.loaded_0:269 
(anonymous function) @ cb=gapi.loaded_0:149 
c.port1.onmessage @ cb=gapi.loaded_0:70** 

回答

0
Service level code 

    authenticateGoogle() { 
      var authProviderUrl = 'https://accounts.google.com/o/oauth2/v2/auth'; 
      var authParameters = { 
       response_type: 'token', 
       client_id: this.configProvider.config.google.clientId, 
       redirect_uri: this.configProvider.config.google.redirectURI, 
       scope: [ 'https://www.googleapis.com/auth/userinfo.email'].join(' ') 
      }; 
      var params = []; 
      for (var k in authParameters) { 
       params.push(k + '=' + authParameters[k]); 
      } 
      var authOpenURI = authProviderUrl + '?' + params.join('&'); 
      window.open(authOpenURI, '_self'); 
     } 

    getUserGoogleProfile(accessToken:string):Observable<any>{ 
      return this.http.get('https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='+ accessToken +'') 
         .map(res => res.json()) 
         .catch(err => Observable.throw(err)); 
     } 

    Caller Code: 

//Google authentication check. 
    if(window.location.hash.match(/^#access_token/)){ 
     var accessToken = window.location.hash.substring(1).split('&')[0].split('=')[1]; 
     this.getUserGoogleProfile(accessToken); 
    } 


    //Get user profile from google with access code. 
     getUserGoogleProfile(accessToken:string) { 
      this.authService.getUserGoogleProfile(accessToken).subscribe(profile => { 
       this.userProfile = new UserProfile(profile.name,profile.email,profile.picture,"google",profile.id); }, 
       err => {console.log(err);}); 

      //Authentication call will go from here to swagger api and if that is successful,set isAuthenticated =true 
      this.userService.isAuthenticated =true; 
      this.router.navigate(['/dashboard']); 
     }