typescript - 当应用程序在 Angular 2 中启动时如何运行服务

标签 typescript angular

我创建了一个服务 SocketService,基本上它初始化套接字让应用程序监听端口。该服务还与一些组件交互。

//socket.service.ts

export class SocketService {
    constructor() {
        // Initializes the socket
    }
    ...
}

我知道 SocketService 的 constructor() 中的代码仅在组件使用 SocketService 时才开始运行。

通常 app.ts 中的代码如下所示:

//app.ts

import {SocketService} from './socket.service';
...
class App {
    constructor () {}
}
bootstrap(App, [SocketService]);

但是,我希望此服务在应用程序启动时运行。所以我弄了一个小技巧,就是在App的constructor()中加入private _socketService: SocketService即可。现在代码如下所示:

//app.ts(新)

import {SocketService} from './socket.service';
...
class App {
    constructor (private _socketService: SocketService) {}
}
bootstrap(App, [SocketService]);

现在可以了。问题是 SocketService 的 constructor() 中的代码有时运行,有时不运行。那么应该如何正确操作呢?

最佳答案

Stuart 的回答指向了正确的方向,但要找到有关 APP_INITIALIZER 的信息并不容易。简短的版本是您可以在任何其他应用程序代码运行之前使用它来运行初始化代码。找了一会,找到解释herehere ,我将对其进行总结,以防它们从网络上消失。

APP_INITIALIZER 是在 angular/core 中定义的。你像这样将它包含在你的 app.module.ts 中。

import { APP_INITIALIZER } from '@angular/core';

APP_INITIALIZER 是一个 OpaqueToken (或自 Angular 4 起的 InjectionToken)引用 ApplicationInitStatus 服务。 ApplicationInitStatus 是一个 multi provider .它支持多个依赖项,您可以在您的提供商列表中多次使用它。它是这样使用的。

@NgModule({
  providers: [
    DictionaryService,
    {
      provide: APP_INITIALIZER,
      useFactory: (ds: DictionaryService) => () => return ds.load(),
      deps: [DictionaryService],
      multi: true
    }]
})
export class AppModule { }

此提供程序声明告诉 ApplicationInitStatus 类运行 DictionaryService.load() 方法。 load() 返回一个 promise ,而 ApplicationInitStatus 会阻止应用程序启动,直到 promise 得到解决。 load() 函数定义如下。

load(): Promise<any> {
  return this.dataService.getDiscardReasons()
  .toPromise()
  .then(
    data => {
      this.dictionaries.set("DISCARD_REASONS",data);
    }
  )
}

设置为字典首先加载,应用的其他部分可以安全地依赖它。

编辑:请注意,无论 load() 方法需要多长时间,这都会增加应用的前期加载时间。如果你想避免这种情况,你可以使用 resolver而不是在你的路线上。

关于typescript - 当应用程序在 Angular 2 中启动时如何运行服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35191617/

相关文章:

Angular <select> 绑定(bind)到对象确认更改或恢复到以前的值

angular - 如何使用 angular 和 typescript 从 .graphql 文件加载查询

直接浏览时找不到 Angular 路由

typescript - Visual Studio Code 中的自动 JSDoc 生成坏了?

TypeScript:可变函数的类型

typescript - 如何修复 `Class constructor LitElement cannot be invoked without ' new'`?

typescript - 将联合映射到接口(interface)属性

javascript - md-select Angular Material 中的错误消息触发器

c# - Angular 7 无法使用 c#.net core api 下载文件

javascript - 在 JavaScript 中创建扁平数组时,如何对匹配的嵌套数组子项进行分组?