加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 服务事件不会正确影响模板

发布时间:2020-12-17 17:15:43 所属栏目:安全 来源:网络整理
导读:在Google中验证,使用Angular2. 首先,在HTML中,我加载谷歌API库: //index.html//...script var googleApiClientReady = function() { ng2Gauth.googleApiClientReady(gapi); } /script script src="https://apis.google.com/js/client.js?onload=googleApiCl
在Google中验证,使用Angular2.

首先,在HTML中,我加载谷歌API库:

//index.html
//...
<script> 
       var googleApiClientReady = function() {
          ng2Gauth.googleApiClientReady(gapi);
      }
    </script>    
    <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
//...

在Angular2服务之后,我处理谷歌身份验证数据并发出事件通知组件,如果谷歌api准备好了:

//google auth service .ts
import {Injectable,EventEmitter} from 'angular2/core';

@Injectable()
export class GoogleAuthService {

    isGoogleApiReady: EventEmitter<boolean>;

    constructor() {
        window['ng2Gauth'] = this; //is it correct way?
        this.isGoogleApiReady = new EventEmitter;       
    }
    //it fires from outside of Angular scope
    public googleApiClientReady(gapi){
        this.gapi.auth.init( () => { 
            this.isGapiReady.emit(true);
        })
    };
//...

在这里,在组件中,我选中复选框,或禁用按钮,并执行其他模板操作.

//gauth component
import {Component} from 'angular2/core';
import {GauthService} from './gauth.service';

@Component({
    selector: 'gauth',template: `<input type="checkbox" [(ngModel)]="isReady"> Api ready

export class GauthComponent {
    constructor (private _gauthService:GauthService) {
        _gauthService.isGoogleApiReady.subscribe( (flag) =>   this.gapiOnReady(flag) )

  public isReady = false
  gapiOnReady(flag: boolean) { //it fires,this.isReady = true;       //but not affect on template correctly
    console.log('gapi loaded') 
    this._gauthService.checkAuth();     
  }
}

看起来所有应该都可以工作但是浏览器中存在奇怪的错误(Chrome,FF) – 如果页面加载在活动浏览器的选项卡上 – 看起来没有任何反应 – 复选框没有检查,如果我在浏览器加载页面时打开其他选项卡,全部没关系.

怎么解决?是Angular bug还是我做错了?

解决方法

将NgZone注入组件并使用zone.run()初始化库代码,这样库代码使用区域修补异步API,Angular知道何时需要运行更改检测

var googleApiClientReady;
constructor(private zone: NgZone) {
} 

public googleApiClientReady(gapi){          
  zone.run(function () { 
    this.gapi.auth.init( () => { 
        this.isGapiReady.emit(true);
    })
  });
}

gapiOnReady(flag: boolean) {
  zone.run(function() {
    this.isReady = true;       //but not affect on template correctly
    console.log('gapi loaded') 
    this._gauthService.checkAuth();   
  });
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读