我正在使用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似乎没有被初始化:我必须设置一个&gt; 500ms超时才能使用它,这很难看。
此代码给出了以下错误:
错误类型错误:无法读取未定义的属性“请求”
请不要:
1-我没有用npm / yarn安装任何东西,我只是使用带有gapi var声明的脚本 2 - 在每次构建之后,代码在没有任何错误的情况下工作,并在第一次加载页面时填充我的表单,然后在一次刷新之后,它每次都会失败。
如何在所有组件之前告诉angular在启动时加载client.js?
谢谢!
答案 0 :(得分:1)
感谢@ADarnal,我终于通过阅读这个主题找到了解决方案:
How to pass parameters rendered from backend to angular2 bootstrap method
我遵循了在computeiro的回答中描述的相同过程 我相当于&#34; BackendRequestClass&#34; class是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(
...
});