所以我有一个在服务中设置selectedCountry
的组件。我有另一个服务从api/${selectedCountry}
获取数据,我希望服务在国家更改时订阅,从而反映数据的变化。有没有办法做到这一点?
这是我目前所拥有的:
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);
}
请让我知道如何做到这一点,或者如果我只是过度思考它。谢谢!
答案 0 :(得分:2)
您需要做的是订阅第一个服务(SettingService
),从第二个服务(我已经粘贴了您的代码片段),并注意那里selectedCountry
属性的更改和然后一旦有更改运行代码。
...
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
}
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);
}