@Self()修饰符用于注入至当前组件或指令中,而不是注入到父组件或父指令中。这意味着当有多个提供相同令牌的服务提供商时,Angular将使用最接近请求的本地提供商。
示例代码:
import { Component, OnInit, Self } from '@angular/core'; import { MyService } from './my.service';
@Component({ selector: 'app-child', template: '
{{ message }}
', }) export class ChildComponent implements OnInit { constructor(@Self() private myService: MyService) {}public message: string;
ngOnInit(): void { this.message = this.myService.getMessage(); } }
在上述代码中,当ChildComponent尝试注入MyService实例时,@Self()装饰器确保使用ChildComponent本地提供商,而不是父组件提供商。