从Google API加载auth2时,更改检测功能无法运行 [英] Change detection doesn't run when loading auth2 from Google API

查看:301
本文介绍了从Google API加载auth2时,更改检测功能无法运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从Angular 2服务中加载脚本 https://apis.google.com/js/api.js?onload=initGapi 为了调用Google API,但每当脚本完成加载和初始化时尝试返回一个值时, async 管道都不想呈现该值

我使用 EventEmitter ,当 gapi时触发。 load() gapi.client.init 已完成,并且observable将订阅到组件中。异步管道似乎不想读取值,直到我单击相同组件内的按钮(并可能触发更改检测)。当我在 ApplicationRef 中使用 tick()时,在组件内强制更改检测不起作用。



加载Google API的服务如下所示:

google-api.service.ts

 从'@ angular / core'导入{Injectable,EventEmitter}; 
从'rxjs / Observable'导入{Observable};

从'../../+home/models'导入{User,Client};

声明var gapi:any;

@Injectable()
export class GoogleApiService {

CLIENT_ID:string ='.... apps.googleusercontent.com';
DISCOVERY_DOCS:string [] = [https://www.googleapis.com/discovery/v1/apis/admin/directory_v1/rest];
SCOPES ='https://www.googleapis.com/auth/admin.directory.user.readonly';

authEmitter:EventEmitter< boolean> = new EventEmitter();

构造函数(){
window ['initGapi'] =(ev)=> {
this.handleClientLoad();
};
this.loadScript();


loadScript(){
let script = document.createElement('script');
script.src ='https://apis.google.com/js/api.js?onload=initGapi';
script.type ='text / javascript';
document.getElementsByTagName('head')[0] .appendChild(script);


handleClientLoad(){
gapi.load('client:auth2',this.initClient.bind(this));


initClient(){
gapi.client.init({
discoveryDocs:this.DISCOVERY_DOCS,
clientId:this.CLIENT_ID,$ b $(b)范围:this.SCOPES
})。then(()=> {
this.authEmitter.emit(true);
});
}

get gapi():Observable< any> {
return this.authEmitter.map(()=>'hello world');


从服务中读取组件



app.component.ts

  import {Component ,来自'@ angular / core'的OnInit}; 
从'rxjs / Observable'导入{Observable};

从'../../+core/services'导入{GoogleApiService};

@Component({
template:`
服务说什么?
{{api $ | async}}
查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆