首页 > 解决方案 > 创建一个单例服务而不需要在 Angular 7 中注入它

问题描述

情况

我一直在尝试找到一种方法来实例化一个服务,该服务将纯粹位于“后台”并监听事件(并做一些事情)——我希望在应用程序初始化时创建它,并被遗忘.

不幸的是,我需要在组件中使用依赖注入,以便实例化服务 - 我采用的大多数路径都导致使用AppComponent's 构造函数。

不过,我不会直接与服务交互(调用方法/属性),并且希望将其排除在与它没有任何直接关系的其他组件/服务之外。


服务

服务和其中的逻辑非常简单。我的服务基于Angular 2教程中的动态页面标题。

该服务将监听NavigationEnd来自 的事件Router,抓取ActivatedRoute,然后使用路由的数据来设置页面标题。

与教程中的示例不同,我创建了自己的服务,而不是将逻辑放在AppComponent; 我想让我的关注点分离保持领先。

页面标题.service.ts:

import { Injectable } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { filter, map, mergeMap } from 'rxjs/operators';

@Injectable()
export class PageTitleService {

  constructor(
    router: Router,
    activatedRoute: ActivatedRoute,
    titleService: Title
  ) {
    router.events
      .pipe(
        filter((event) => event instanceof NavigationEnd),
        map(() => activatedRoute),
        map((route) => {
          while (route.firstChild) {
            route = route.firstChild;
          }

          return route;
        }),
        filter((route) => route.outlet === 'primary'),
        mergeMap((route) => route.data)
      )
      .subscribe((routeData) => titleService.setTitle(routeData['title']));
  }

}

显然,服务本身将依赖依赖注入来使用RouterActivatedRouteTitle服务。


问题

我目前知道实例化此服务的唯一方法是使用依赖注入到另一个组件/服务中。

例如在app.component.ts

export class AppComponent implements OnInit {

  constructor(
    pageTitleService: PageTitleService, // inject the service to instantiate it
    // ... other services
  ) { }

  ngOnInit() {
    // do stuff with other services, but not the pageTitleService
  }

}

问题是,如果可能的话,我想避免这样做。


问题

是否可以在组件/服务以外的地方实例化服务?


可能性?

在加载应用程序的其余部分之前,我确实有一个app-load.module.ts,它会进行一些前期初始化:

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

import { OrganisationService } from './core/organisation/organisation.service';

export function initApp(organisationService: OrganisationService) {
  return () =>
    organisationService
      .initialize()
      .then(() => window.document.documentElement.classList.remove('app-loading'));
}

@NgModule({
  imports: [],
  declarations: [],
  providers: [
    OrganisationService,
    { provide: APP_INITIALIZER, useFactory: initApp, deps: [OrganisationService], multi: true }
  ]
})
export class AppLoadModule { }

我可以PageTitleService在这里,某处实例化吗?

或者,有更好的地方/方法吗?

提前致谢。

标签: angularservicesingleton

解决方案


只是观察一下为什么注入一个组件(App 组件)不会是一个坏主意:

  1. 在浏览器窗口中显示标题是应用程序的要求,而应用程序组件实际上是您的应用程序的容器(或根)。
  2. 那么我们不能说及时更新标题是应用程序(应用程序组件)关心的问题吗?
  3. 我理解的服务可以看作是一个助手,App 组件可以使用这个服务来更新标题
  4. 您可以init在服务中有一个方法,该方法将从应用程序组件中调用,以便它可以开始侦听路由器事件并更新标题。这使得它非常必要,也很明确,如果需要,您可以将调用此 init 方法转移到其他组件。

推荐阅读