等待第 3 方 JS 库在 Angular 2 服务中完成初始化的最佳方法? [英] Best way to wait for 3rd-party JS library to finish initializing within Angular 2 service?

查看:11
本文介绍了等待第 3 方 JS 库在 Angular 2 服务中完成初始化的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Angular 服务中包装一个 3rd-party JS 库.我如何保证第 3 方 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?

你能看看下面的代码并告诉我这是否是一个良好的编码习惯?我在服务的构造函数中设置了一个承诺(最终会实现的承诺),我的服务方法取决于该承诺的成功(请参阅 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.

这是描述全局方法的相应 plunkr:https://plnkr.co/edit/ooMNzEw2ptWrumwAX5zP?p=preview.

Here is a corresponding plunkr describing the global approach: https://plnkr.co/edit/ooMNzEw2ptWrumwAX5zP?p=preview.

这篇关于等待第 3 方 JS 库在 Angular 2 服务中完成初始化的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆