What's the best way to inject one service into another in angular 2 (Beta)?

前端 未结 7 1533
庸人自扰
庸人自扰 2020-11-22 05:25

I know how to inject a service into a component (via @Component), but how can I use DI to pass around services outside of components?

In other words, I don\'t want t

7条回答
  •  天命终不由人
    2020-11-22 05:49

    Somehow @Injectable doesn't work for me in Angular 2.0.0-beta.17 when wiring ComponentA -> ServiceB -> ServiceC.

    I took this approach:

    1. Reference all services in the @ComponentA's providers field.
    2. In ServiceB use the @Inject annotation in the constructor to wire ServiceC.

    Run this Plunker to see an example or view code below

    app.ts

    @Component({selector: 'my-app',
        template: `Hello! This is my app 

    `, directives: [OverviewComponent] }) class AppComponent {} bootstrap(AppComponent);

    overview.ts

    import {Component, bind} from 'angular2/core';
    import {OverviewService} from "../services/overview-service";
    import {PropertiesService} from "../services/properties-service";
    
    @Component({
        selector: 'overview',
        template: `Overview listing here!`,
        providers:[OverviewService, PropertiesService] // Include BOTH services!
    })
    
    export default class OverviewComponent {
    
        private propertiesService : OverviewService;
    
        constructor( overviewService: OverviewService) {
            this.propertiesService = overviewService;
            overviewService.logHello();
        }
    }
    

    overview-service.ts

    import {PropertiesService} from "./properties-service";
    import {Inject} from 'angular2/core';
    
    export class OverviewService {
    
        private propertiesService:PropertiesService;
    
        // Using @Inject in constructor
        constructor(@Inject(PropertiesService) propertiesService:PropertiesService){
            this.propertiesService = propertiesService;
        }
    
        logHello(){
            console.log("hello");
            this.propertiesService.logHi();
        }
    }
    

    properties-service.ts

    // Using @Injectable here doesn't make a difference
    export class PropertiesService {
    
        logHi(){
            console.log("hi");
        }
    }
    

提交回复
热议问题