Open eternallycyf opened 9 months ago
@Module({ imports: [PersonModule], controllers: [PersonController], providers: [PersonService], exports: [PersonService], }) controllers 只能被注入 providers 里可以被注入,也可以注入别的对象
// 1. @Module({ providers: [PersonService], }) constructor(private readonly personService: PersonService) {} // 2. @Inject(PersonService) private personview: PersonService @Module({ providers: [PersonService], }) // 3. providers: [ { provide: PersonService, useClass: PersonService } ] constructor(private readonly personService: PersonService) {} ... // 4. exports 也要字符串 providers: [ { provide: 'person_service', useClass: PersonService } ], exports: ['person_service'], constructor(@Inject('person_service') private readonly personService) {} @Inject('person_service') private readonly PersonService: PersonService // 5.useValue providers: [ { provide: 'person', useValue: { name: 'zs', age: 12, }, }, ], @Inject('person') private readonly person: {name: string, age: number}; // this.person.name // 6.useFactory { provide: 'person2', useFactory() { return { name: 'bbb', desc: 'cccc' } } } @Inject('person2') private readonly person2: {name: string, desc: string}; // 7.useFactory 支持通过参数注入别的 provider { provide: 'person3', useFactory(person: { name: string }, appService: AppService) { return { name: person.name, desc: appService.getHello() } }, inject: ['person', AppService] } // 8. 支持异步 { provide: 'person5', async useFactory() { await new Promise((resolve) => { setTimeout(resolve, 3000); }); return { name: 'bbb', desc: 'cccc' } }, }, // 9.useExisting 指定别名 { provide: 'person4', useExisting: 'person2' }