Angular 2值未在html中更新

时间:2017-06-06 05:54:49

标签: facebook angular

我正在开发需要登录facebook的应用程序。这是我的ts文件

 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(facebook attr)的onlogin函数的最佳方式。

由于

2 个答案:

答案 0 :(得分: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
 }

答案 1 :(得分:0)

这是因为fbAsyncInit猴子修补事件监听器无法识别zone.js方法的返回事件。换句话说,你在角度区域之外工作。

您应该在组件中注入NgZone,然后使用run重新输入:

constructor(private _ngZone: NgZone){}

ngOnInit() {
   this.initialize();
}

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