等待第三方JS库在Angular 2服务中完成初始化的最佳方法? [英] Best way to wait for 3rd-party JS library to finish initializing within Angular 2 service?
问题描述
我将第3方JS库包装在Angular服务中.如何保证第三方JS库已加载/初始化/等.在使用我的服务之前?
I'm wrapping a 3rd-party JS library in an Angular service. How can I guarantee that the 3rd-party JS library is loaded/initialized/etc. before using my service?
您能看看下面的代码,并告诉我这是否是良好的编码习惯吗?我正在服务的构造函数中设置一个Promise(最终将兑现的承诺),并且我的服务方法取决于该Promise的成功(请参见getMessages
).
Can you take a look at the following code and tell me if this is a good coding practice? I'm setting up a promise in the service's constructor (promise that will eventually be fulfilled) and I have the service methods depend on the success of that promise (see getMessages
).
@Injectable()
export class GmailService {
private _readyPromise;
// Load Gmail API client library.
// gapi.client.load() returns a promise.
constructor() {
this._readyPromise = gapi.client.load('gmail', 'v1');
}
private ready():Promise {
return this._readyPromise;
}
// Return Gmail messages for the current user.
getMessages() {
return this.ready().then(() => {
return gapi.client.gmail.users.messages.list({
'userId': 'me'
}).then(resp => console.log(resp));
});
}
}
在该示例中,我正在使用Gmail API for JavaScript,事实证明gapi.client.load()
已经返回了promise,从而简化了代码.在另一种情况下,我本可以创建自己的诺言,并在满足特定条件时手动履行诺言.
In that exemple, I'm using the Gmail API for JavaScript and it turns out that gapi.client.load()
already returns a promise, which simplifies the code. In a different scenario I could have created my own promise and fulfilled it manually when a specific condition is met.
推荐答案
您的方法似乎还不错!另一个方法是在加载Gmail API库后引导您的应用程序:
Your approach seems fine! Another one would be to bootstrap your application after your Gmail API library is loaded:
var app = platform(BROWSER_PROVIDERS)
.application([BROWSER_APP_PROVIDERS, appProviders]);
gapi.client.load('gmail', 'v1').then(() => {
return app.bootstrap(AppComponent);
});
这样,您可以确定在应用程序中使用该库时已准备好.
This way you will be sure that the library is ready when using it within your application.
以下是描述全局方法的相应插件: https://plnkr.co/edit/ooMNzEw2ptWrumwAX5zP?p =预览.
Here is a corresponding plunkr describing the global approach: https://plnkr.co/edit/ooMNzEw2ptWrumwAX5zP?p=preview.
这篇关于等待第三方JS库在Angular 2服务中完成初始化的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!