2016-11-16 47 views
0

所以我有一個組件在服務中設置selectedCountry。而且我有另一項服務從api/${selectedCountry}獲取數據,我希望服務在國家變更時訂閱,從而反映數據的變化。有沒有辦法做到這一點?基於其他服務的Angular 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); 
} 

請讓我知道如何做到這一點,或者如果我只是它得太多。謝謝!

回答

2

您需要做的是訂閱第二個服務(您假設已粘貼的代碼段)中的第一個服務(SettingService),並觀察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}'保持爲空:/ – taropoo