How to inject service into class (not component)

后端 未结 5 2157
醉梦人生
醉梦人生 2020-11-30 02:16

I want to inject a service into a class that is not a component.

For example:

Myservice

import {Injectable} from \'         


        
5条回答
  •  独厮守ぢ
    2020-11-30 02:55

    locator.service.ts

    import {Injector} from "@angular/core";
    
    export class ServiceLocator {
        static injector: Injector;
    }
    

    app.module.ts

    @NgModule({ ... })
    
    export class AppModule {
        constructor(private injector: Injector) {
            ServiceLocator.injector = injector;
        }
     }
    

    poney.model.ts

    export class Poney {
    
        id: number;
        name: string;
        color: 'black' | 'white' | 'brown';
    
        service: PoneyService = ServiceLocator.injector.get(PoneyService); // <--- HERE !!!
    
        // PoneyService is @injectable and registered in app.module.ts
    }
    

提交回复
热议问题