[英]Load Angular 5 component after gapi has been loaded
我正在使用CLI编写一个angular 5应用程序。 我正在使用gapi来检索用户数据以便填充表单。
客户端脚本包含在index.html文件中:
<head>
<meta charset="utf-8">
<script src="https://apis.google.com/js/client.js"></script>
...
</head>
这是我调用的组件:
userProfileModel: UserProfileModel = new UserProfileModel();
ngOnInit() {
this.form = this.toFormGroup();
this.onFormChanges();
this.userService
.getUserById(this.userId)
.then(usr => {
this.mapModel(usr.result['profile']);
})
.then(() => {
this.form.patchValue(this.userProfileModel);
});
}
和userService的方法:
declare var gapi: any;
export class UserService {
getUserById(id: number) {
return gapi.client.request({
method: 'GET',
'path': this.constants['endpoint_user_getbyid'] + '/' + id,
'root': this.constants['api_url']
});
}
...
}
问题是,我的组件加载完成后,gapi似乎没有立即初始化:我必须设置一个> 500ms的超时时间才能使用它,这很丑陋。
此代码给我以下错误:
错误TypeError:无法读取未定义的属性“请求”
请不要:
1-我没有用npm / yarn安装任何东西,我只是在使用带有gapi var声明的脚本。
2-每次构建后,代码均能正常工作,并在首次加载页面时填充我的表单,然后刷新一次后,每次都会失败。
我怎样才能告诉angular在启动所有组件之前先加载client.js?
谢谢 !
感谢@ADarnal,我终于通过阅读此主题找到了解决方案:
我遵循了computeiro的答案中所述的相同过程。
我相当于“ BackendRequestClass”类的是GapiService。
在此Gapi服务中,load方法允许我在执行任何其他调用之前先加载gapi:
/* GapiService */
loadGapi() {
return new Promise((resolve, reject) => {
gapi.load('client', () => {
gapi.client.init({apiKey: 'AIzaSyD5Gl9...'}).then(() => {
resolve(gapi.client);
})
});
});
}
// Method used in any component
getUserById(id: number) {
return gapi.client.request({
method: 'GET',
'path': this.constants['endpoint_user_getbyid'] + '/' + id,
'root': this.constants['api_url']
});
}
最后; 在我的组件中,我注入了gapiService,并且能够在组件init上使用client.request!
ngOnInit() {
this.gapiService
.getUserById(5066549580791808)
.then(
...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.