1

동일한 서비스의 두 인스턴스간에 데이터를 공유 할 수 있습니까?Angular2는 같은 서비스의 두 인스턴스간에 데이터를 공유합니다

DateService.ts

private _selectedDate: Date = new Date(); 

private _mode = 'YEAR'; //can be DAY,WEEK,MONTH also 

set selectedDate(newSelectedDate) { 
     this._selectedDate = newSelectedDate; 
    } 

    get selectedDate() { 
     return this._selectedDate; 
    } 

set mode(newMode) { 
     this._mode = newMode; 
    } 

    get mode() { 
     return this._mode; 
    } 

nextDate() { 
     //based on mode this will change the date 
    // if the mode is year then this gives next year 
    // if the mode is month then next month etc... and updates the date 
    } 

내 응용 프로그램에서 여러 페이지에 사용할 필요가 같은 날짜. 하지만 모드이 서비스를 사용하는 구성 요소에 맞게 지정하고 싶습니다. 나는이 구성 요소에서 nextDate 버튼을 클릭했을 때이 구성 요소에서 nextDate를 클릭하면 그 다음 날에 가야

<someother-component [(date)]="dateService.selectedDate" [(mode)]="DAY"></someother-component> 

<some-component [(date)]="dateService.selectedDate" [(mode)]="YEAR"></some-component> 

+2

다른 서비스를 사용하여이 서비스를 두 서비스 인스턴스에 모두 주입하여 데이터를 공유 할 수 있습니다. –

+0

@ GünterZöchbauer는 한 서비스를 다른 서비스에 주입하는 방법을 알려 주실 수 있습니까? 이 생성자 (@Inject (DateService) dateService) { } 을 시도했지만 작동하지 않습니다. –

+0

@ GünterZöchbauer 알았습니다. 감사!! –

답변

1

나는 모드를 통과 할 것 내년에 가야 매개 변수로. Component1에서

:

private mode = 'YEAR'; 

nextDate = this.dateService.nextDate(this.mode); 

Component2 물 :

private mode = 'DAY'; 

nextDate = this.dateService.nextDate(this.mode); 

DateService 물 :

nextDate(mode) { 
    // do stuff with the mode. mode will be different depending who calls this function. 
    // If Component1 calls, mode will be YEAR. If Component2 calls, mode will be DAY. 
} 

기본적으로 DateService에서 nextDate()으로 전화 할 때마다 해당 모드를 매개 변수로 전달하고 설정했는지 확인하십시오.