Angular 4 - 无法从服务中的函数获取数据

时间:2018-03-15 03:32:14

标签: angular

我有一些组件需要使用相同的参考数据,但我不太清楚如何操作。我只想写一个收集数据的http服务和一个返回数据的函数。我希望通过导入服务在我的组件中的任何地方使用该功能。

这是我尝试过的。

example.service.ts:

// http get
getRefCountriesService(): Observable<any[]> {
   this.countries = this.http.get<any[]>(this.refCountryListUrl);
   return this.countries;
}

// function which returns the data
getCountries(): any {
this.getRefCountriesService()
  .subscribe(countries => {
    this.countries = countries['_embedded']['refCountries'];
    return this.countries;
  });
}

example.component.ts

//here is where I want to get the data to a variable
ngOnInit() {
   this.countries = this.exampleService.getCountries();
}

我必须错过一些非常简单的事情,请帮忙。

3 个答案:

答案 0 :(得分:0)

您将在此处返回this.countries

getRefCountriesService(): Observable<any[]> {
   this.countries = this.http.get<any[]>(this.refCountryListUrl);
   return this.countries;
}

但是您没有映射数据,所以一旦服务响应到来,您将无法获得它。当你写的时候

   this.countries = this.http.get<any[]>(this.refCountryListUrl);
   return this.countries;

这是一个承诺,而不是国家,所以你写的是这样的

getRefCountriesService(): Observable<any[]> {
    return this.http.get<any[]>(this.refCountryListUrl).map(res => {
        this.countries = res.json()
    });
}

如果有任何问题,请告诉我

答案 1 :(得分:0)

回调return中的

subscribe值并不意味着从函数中返回值。

相反,您可以直接订阅getRefCountriesService以获得您想要的内容

ngOnInit() {
  this.exampleService
      .getRefCountriesService()
      .subscribe(countries => {
    this.countries = countries['_embedded']['refCountries'];
  });
}

出于以下评论的目的,您可以在服务map使用getRefCountriesService运算符将此功能作为一项常用功能:

getRefCountriesService(): Observable<any[]> {
  //do not save here this.countires because it is Observable => just return it.
  return this.http.get<any[]>(this.refCountryListUrl).map(countries => countries['_embedded']['refCountries']);
}

// component
ngOnInit() {
  this.exampleService
      .getRefCountriesService()
      .subscribe(countries => {
        this.countries = countries;
      });
}

答案 2 :(得分:0)

您滥用this.countries变量。 如果您将this.countries用作变量。请参考以下内容:

example.service.ts:

// http get
getRefCountriesService(): Observable<any[]> {
   //do not save here this.countires because it is Observable => just return it.
   return this.http.get<any[]>(this.refCountryListUrl);
}

// function which returns the data
getCountries(): any {
this.getRefCountriesService()
  .subscribe(countries => {
    //when this http service success, this.countries can save data.
    this.countries = countries['_embedded']['refCountries'];

  });
}

example.component.ts

//here is where I want to get the data to a variable
ngOnInit() {
   //you can call the getCountries function here, then this.countries will have data when http service is complete in the getCountries() function.
  //you do NOT need to use this.countries here
   this.exampleService.getCountries();
}