2016-11-16 117 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