2017-06-06 65 views
0

我正在開發一個需要facebook登錄的應用程序。這裏是我的TS文件Angular 2的值在html中不更新

ngOnInit() { 
    setTimeout(() => { 
     this.initialize(); 
    }) 
    } 

    initialize() { 
    (function (d, s, id) { 
     var js, fjs = d.getElementsByTagName(s)[0]; 
     if (d.getElementById(id)) return; 
     js = d.createElement(s); js.id = id; 
     js.src = "//connect.facebook.net/en_US/sdk.js"; 
     fjs.parentNode.insertBefore(js, fjs); 
    }(document, 'script', 'facebook-jssdk')); 


    setTimeout(() => { 
     window.fbAsyncInit = () =>{ 
     FB.init({ 
      appId: 'your-app-id', //I gave my app id here 
      cookie: true, // enable cookies to allow the server to access 
      // the session 
      xfbml: true, // parse social plugins on this page 
      version: 'v2.8' // use graph api version 2.8 
     }); 
     this.checkFBLoginStatus(); 
     } 
    }) 

    } 

    checkFBLoginStatus() { 
    FB.getLoginStatus((response) =>{ 
     this.verifyResponse(response); 
    }); 
    } 


verifyResponse(response){ 
    this.response = response; 

    console.log(this.response) // I am getting the console output 
} 

這裏是我的HTML

<!--For Testing purpose--> 
Response is-> 
<p *ngIf="response">{{response.status}}</p> 
<!--For Testing purpose--> 

<button *ngIf="response && response.status && response.status == 'unknown'" class="btn blue fb-login-button" (click)="loginUsingFacebook()"><span class="fa fa-facebook white-text"></span>Login Using Facebook</button> 

<button *ngIf="response && response.status && response.status == 'not_authorized'" class="btn blue fb-login-button" (click)="continueUsingFacebook()"><span class="fa fa-facebook white-text"></span>Continue Using Facebook</button> 

<button *ngIf="response && response.status && response.status == 'connected'" class="btn blue fb-login-button" (click)="logoutFacebook()"><span class="fa fa-facebook white-text"></span>Logout Facebook</button> 

的response.status是顯示在控制檯中。但它沒有被綁定到HTML。所以我無法看到相應的按鈕。

我想檢測用戶是否登錄或如果沒有,什麼是最好的方式,我可以捕獲JavaScript腳本的onlogin函數(facebook attr)打字稿。

感謝

回答

0

這是因爲從fbAsyncInit方法的返回事件不是由zone.js猴子修補事件偵聽器的認可。換句話說,你在角度區外工作。

你應該在你的組件注入NgZone,並使用run重新輸入:

constructor(private _ngZone: NgZone){} 

ngOnInit() { 
    this.initialize(); 
} 

initialize() { 
    window.fbAsyncInit = () => { 
    this._ngZone.run(() => { 
     FB.init({ 
      ... 
     }); 
     this.checkFBLoginStatus(); 
    }); 
    } 
} 
1

在這裏,您將不得不手動刷新模型數據。爲此,你可以使用NgZone

在下面的方式

import {Component, NgZone} from '@angular/core'; 

constructor() { 
    this.zone = new NgZone({enableLongStackTrace: false}); 
} 


verifyResponse(response){ 
    this.zone.run(() => { 
     this.response = response; 
    }); 

    console.log(this.response) // I am getting the console output 
}