代码之家  ›  专栏  ›  技术社区  ›  user2024080

`RxJS `在do请求时在subcribe上引发错误

  •  0
  • user2024080  · 技术社区  · 8 年前

    我正在使用observable发出请求。并试图转载价值观。但在typescript上获取错误。有人来帮我吗?

    我喜欢这样做:

    public getCountry(lat,lan):Observable<any>{
        return this.http.get(this.googleApi+lat+','+lan+'&sensor=false').subscribe(data => {
            return this.genertedData(data);
        } );
    }
    

    但得到的错误如下:

    Observable Error

    更新

     public getCountry(lat,lan):Observable<any>{
    
            return this.http.get(this.googleApi+lat+','+lan+'&sensor=false').map( data => {
    
                data.results.map( array => {
                    let details = array.address_components.find( obj => obj.types.includes("country") );
                    this.countryDetails.countryLongName = details.long_name;
                    this.countryDetails.countryShortName = details.short_name;
                })
    
                return this.countryDetails;
            })
    
        }
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   Philipp Meissner    8 年前

    问题是您的返回类型状态 Observable<any> ,当你实际返回 this.genertedData(data) 返回(提示:听起来像是函数中的输入错误。我想应该调用它 generatedData ?)。

    最佳实践是将http调用移动到服务中 subscribe 返回到其 Observable 在您的组件中。

    可以这么说:

    // => service.ts
    public getCountryObservable(lat,lan):Observable<any> {
        return this.http.get(this.googleApi+lat+','+lan+'&sensor=false');
    }
    

    您的组件看起来像:

    // => component.ts
    export class YourComponent {
      constructor(public yourService: YourService) {}
      getCountry(lat, lan): whateverDataTypeYourGeneratedDataReturns {
        this.yourService.getCountryObservable(lat, lan).subscribe((data) => {
          this.data = this.generatedData(data);
        });
      }
    }
    
        2
  •  1
  •   Philipp Meissner    8 年前

    因为函数的返回类型是 Observable<any> ,我想它应该会回来 this.http.get(this.googleApi+lat+','+lan+'&sensor=false')