Angular中的注入器(Injector)用于创建和解析依赖项。注入上下文是指一个注入器层次结构,在该层次结构中,每个模块都有自己的注入器。这种层次结构可确保每个组件都有自己的依赖项,并且这些依赖项不会与其他组件共享。
在Angular 16+中,要在注入上下文中提供服务,你需要在服务上使用@Injectable()装饰器。然后,在组件中,你可以使用构造函数中的注入器参数来获取服务的实例。
下面是一个示例代码,展示了如何在Angular中使用注入上下文:
// my-service.ts
import { Injectable } from '@angular/core';
@Injectable() export class MyService { constructor() { }
log(message: string) {
console.log(MyService log: ${message}
);
}
}
// my-component.ts
import { Component } from '@angular/core'; import { MyService } from './my-service';
@Component({ selector: 'my-component', template: '', }) export class MyComponent { constructor(private myService: MyService) { }
onClick() { this.myService.log('Button clicked'); } }
在以上示例代码中,注入上下文的层次结构是通过在MyComponent组件中注入MyService服务来创建的。在这个注入上下文中,每个组件都有自己的MyService实例。所以,MyComponent的MyService实例不会与其他组件共享,并且可以对其进行修改,而不会影响其他组件的MyService实例。