Angular 两种依赖注入的实现方法介绍

发布时间 2023-11-19 21:55:07作者: JerryWang_汪子熙

方法1:使用 Constructor parameter

@Injectable(...)
export class Service {
	constructor(
		protected serviceA: ServiceA,
		protected serviceB: ServiceB,
		@Inject(PLATFORM_ID) protected platformId: any
	){}
}

方法2:使用 Angular 14 引入的 inject 函数

/* Injection via `inject` function */

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

@Injectable()
export class Service {
	  protected serviceA: ServiceA;
	
	  constructor(){
	    // `inject` allowed in constructor body:
		  this.serviceA = inject(ServiceA);
	  }

	// `inject` allowed in property initialization:
	protected serviceB = inject(ServiceB); //note: property type is automatically derived
	protected platformId = inject(PLATFORM_ID); // you can inject injection tokens as well
}

注意上面代码里的 PLATFORM_ID.

Angular 的依赖注入系统是其核心功能之一,它允许开发者轻松管理组件、服务等之间的依赖关系。在 Angular 中,InjectionToken 是一种特殊类型的 token,它用于在依赖注入系统中注册依赖关系。PLATFORM_ID 就是其中一个重要的 InjectionToken,它用于检测应用当前运行的平台。

在 Angular 应用中,我们可能会在不同的平台上运行,比如浏览器、服务器端或者移动端。这些平台上的执行环境可能会有一些差异,而 PLATFORM_ID 就提供了一种标识当前平台的方式。它是一个注入令牌,用于告诉 Angular 我们的应用当前是在哪个平台上运行。

下面是一个简单的示例,演示了如何使用 PLATFORM_ID。在这个示例中,我们假设有一个服务需要根据当前运行的平台执行不同的逻辑。这个服务可以通过 PLATFORM_ID 来判断当前的平台。

import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';

// 定义一个服务,它依赖于 PLATFORM_ID
@Injectable({
  providedIn: 'root',
})
export class PlatformService {
  // 在构造函数中通过 @Inject 注入 PLATFORM_ID
  constructor(@Inject(PLATFORM_ID) private platformId: Object) {}

  // 一个根据平台执行不同逻辑的方法
  performPlatformSpecificLogic(): string {
    if (isPlatformBrowser(this.platformId)) {
      return '在浏览器中执行的逻辑';
    } else if (isPlatformServer(this.platformId)) {
      return '在服务器中执行的逻辑';
    } else {
      return '在其他平台中执行的逻辑';
    }
  }
}

在上面的示例中,PlatformService 服务依赖于 PLATFORM_ID。在构造函数中,通过 @Inject(PLATFORM_ID)PLATFORM_ID 注入到 platformId 变量中。然后,通过 isPlatformBrowserisPlatformServer 方法来检测当前的平台,并根据不同的平台执行不同的逻辑。

这种方式的好处在于,我们可以根据应用运行的平台来动态地调整服务的行为,使得我们的应用更具有灵活性和可移植性。

另外,PLATFORM_ID 还可以在一些其他场景中使用,比如在应用初始化时执行一些特定于平台的代码,或者在服务中根据平台加载不同的配置等等。总之,它为开发者提供了一种方便的方式来处理跨平台的逻辑。