user2024080
user2024080

Reputation: 5101

`RxJS` throws error on subcribe when do request

I am making a request using observable. and trying to subcribe the value. But getting error on typescript. any on help me?

I like to do this:

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

But getting error as follows:

Observable Error

UPDATES

 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;
        })

    }

Upvotes: 0

Views: 41

Answers (2)

Joseph Wu
Joseph Wu

Reputation: 5028

Since the return type of the function is Observable<any>, I guess it should just return this.http.get(this.googleApi+lat+','+lan+'&sensor=false')

Upvotes: 1

Philipp Meissner
Philipp Meissner

Reputation: 5482

The problem is that your return type states Observable<any>, where as you actually return whatever this.genertedData(data) returns (Hint: Sounds like a typo in your function. Guess it should be called generatedData ?).

Best practice would be to move the http call into a service and subscribe to its returned Observable within your component.

So to speak:

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

Your component would look something like:

// => 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);
    });
  }
}

Upvotes: 2

Related Questions