Angular 2 http调用url基于另一个服务

时间:2016-11-16 01:46:42

标签: angular

所以我有一个在服务中设置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);  
}

请让我知道如何做到这一点,或者如果我只是过度思考它。谢谢!

1 个答案:

答案 0 :(得分: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);  
}