2017-01-25 5 views
0

2 개의 서비스를 사용하는 구성 요소가 있습니다.angular2 service instancied 2 times

export class UseComponent {  
    constructor(private _service1: Service1, 
       private _service2: Service2){} 

두 번째 서비스에는 첫 번째 서비스에 존재하는 메소드가 필요합니다. UseComponent 메소드 getLabel를 사용하는 경우에 따라서 I는 모듈

@NgModule({ 
    imports: [.....], 
    declarations: [.....], 
    providers: [Service1, Service2] 
    }) 
    export class UseModule { } 

또한 서비스 제

export class Service2{ 

constructor(private _service1: Service1) {}; 

getLabel(): string{ 
    return this._service1.getLanguageLabel(); 
} 

제공자의 fisrty 서비스되는 주입 때 구성 요소의 서비스 1 다시 (제 instanciation를 instancied되고 초기화 됨)

이 두 번째 인스턴스가 필요한 이유는 무엇입니까? 어떻게 피하는가? 일반적으로

+0

UseComponent에 provider를 설정 했습니까? –

답변

1

작품 : https://plnkr.co/edit/pWgQ5iVNVVGmHBZsv2SD?p=preview

것은 이러한 서비스는 다른 module의 제공자 목록에없는 것을주의하십시오.

@Injectable() 
export class Service1 { 

    constructor() { 
    addLog('created service 1'); 
    } 

    public anyFunc() { 
    return "huhu"; 
    } 
} 

@Injectable() 
export class Service2 { 

    constructor(private _srv1: Service1) { 
    addLog('created service 2'); 
    } 

    public anyFunc() { 
    return this._srv1.anyFunc(); 
    } 
} 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{name}}</h2> 
    </div> 
    <p *ngFor="let log of logs | async">{{log}}</p> 
    `, 
}) 
export class App { 
    name:string; 
    private logs = logs; 

    constructor(private _srv2: Service2) { 
    this.name = 'Angular2' 

    addLog(this._srv2.anyFunc()); 
    } 
} 

@NgModule({ 
    imports: [ BrowserModule ], 
    declarations: [ App ], 
    providers: [Service1, Service2], 
    bootstrap: [ App ] 
}) 
export class AppModule { }