[英]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.