2016-11-16 12 views
0

サービス内にselectedCountryを設定するコンポーネントがあります。そして私はapi/${selectedCountry}からデータを取得する別のサービスを持っています。国の変更が行われたときにサービスを購読したいので、データの変更が反映されます。それを行う方法はありますか?角2 HTTP呼び出しの別のサービスに基づくURL

は、ここで私は、現在持っているものです。

private url: string; 
private headers: Headers; 
private options: RequestOptions; 

constructor(private http: Http, 
    private settingService: SettingService) { 
    this.url = `/api/${this.settingService.selectedCountry}`; 
    this.headers = new Headers({ 'Content-Type': 'application/json' }); 
    this.options = new RequestOptions({ headers: this.headers }); 
} 

getTasks(): Observable<Task[]> { 
    return this.http.get(this.url) 
     .map(response => response.json()) 
     .catch(this.handleError); 
} 

は私がこれを行う方法を教えてください、または私はちょうどそれをoverthinkingています。ありがとう!

答えて

2

2番目のサービス(SettingService)に2番目のサービス()を購読して、それにselectedCountryプロパティの変更を監視してから変更を実行するとコード。

SettingService

... 
import { Subject } from 'rxjs/Subject' 
import { Observable } from 'rxjs/Rx' 
... 

export class SettingService{ 
    ... 
    // Observable string sources 
    private selectedCountrySource = new Subject<string>() 

    // Observable string streams 
    selectedCountryChange$ = this.selectedCountrySource.asObservable() 
    ... 

    //Wherever you are changing the selected country add the next line 
    this.selectedCountrySource.next(selectedCountry) 

    //What this does is emit that there is a change. The selectedCountry  
    //parameter will be the new country 
} 

OtherService

private url: string; 
private headers: Headers; 
private options: RequestOptions; 

constructor(private http: Http, private settingService: SettingService) { 
    this.url = `/api/${this.settingService.selectedCountry}`; 
    this.headers = new Headers({ 'Content-Type': 'application/json' }); 
    this.options = new RequestOptions({ headers: this.headers }); 

    //Subscribe to the SettingService for changes 
    sessionService.selectedCountryChange$.subscribe(
     newSelectedCountry => { 
      this.url =`/api/${newSelectedCountry}`; 

      //Call getTasks if needed to update 
      this.getTasks() 
    }) 
} 

getTasks(): Observable<Task[]> { 
    return this.http.get(this.url) 
    .map(response => response.json()) 
    .catch(this.handleError); 
} 
+0

'注射をSettingService'、おそらくフィールドとして' selectedCountry'を定義してください? – echonax

+0

すぐにお返事ありがとうございます。しかし、 '$ {this.settingService.selectedCountry}'はnullに戻りました:/ – taropoo

関連する問題