Search code examples
angularionic-frameworkobservableangular8ionic5

ionic 5 : TypeError: Cannot read property 'subscribe' of undefined


I have this service in IONIC 5 :


import { HttpClient } from '@angular/common/http';
.
.
.
getPlaces(placeId: string) {
return this.httpClient.get(
        `https://test.com/offered-place/${placeId}.json`)
}
.
.
.

In my component when i try to call may service's function and subscribe to it:


this.myService.getPlaces().subscribe(()=>{})...

I got the error : TypeError: Cannot read property 'subscribe' of undefined.


but when I try to subscribe within the service it works !!

ps:

  • IONIC 5

my service is injected in the constructor of my component (where I got my error)

my service is annotated :

@Injectable({ providedIn: 'root' })

  • IDE Visual Code

Thanks in advance


Solution

  • In the component it won't work because the getPlaces function requires placeID and from the component you are not sending the value to the function when you are calling

    this.myService.getPlaces().subscribe(()=>{})...
    

    so you have to pass placeID in this and subscribe it by adding a reference like i have written result. Now in result you will have the data from the api.

    this.myService.getPlaces(placeID should be passed here).subscribe((result)=>{console.log(result);})...
    

    and in the service add Observale to the function

    getPlaces(placeId: string): Observable<any> {
    return this.httpClient.get(
            `https://test.com/offered-place/${placeId}.json`)
    }