Injection of Generic Services in Angular

后端 未结 2 886
滥情空心
滥情空心 2020-12-14 07:10

Will Angular inject more than one instance of a generic Service if it is invoked across Component constructors using different Types?

I have a lot of Services that a

2条回答
  •  青春惊慌失措
    2020-12-14 07:39

    This is a simple solution:

    // service and models
    export class User {
      firstName: string
    }
    
    export class Admin {
      lastName: string
    }
    
    @Injectable()
    export class GenericService{
      item: number = Math.random();
      GetAll(): Array {
        let output = [];
        console.log(this.item); // each instance has own value
        return output;
      }
    }
    

    Then set your service in module through useFactory:

    providers: [
      { provide: 'UserService', useFactory: () => (new GenericService()) },
      { provide: 'AdminService', useFactory: () => (new GenericService()) },
    ],
    

    and inject your service with @Inject decorator:

    constructor(
      @Inject('UserService') private userService: GenericService,
      @Inject('AdminService') private adminService: GenericService
    ) { }
    

    Keep in mind it is better to use InjectionToken ( OpaqueToken is deprecated) for your provider token.I have used string just for simplicity.

提交回复
热议问题