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

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

我在 IONIC 5 中有这项服务:


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

在我的组件中,当我尝试调用可能服务的功能并订阅它时:


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

我收到错误:类型错误:无法读取未定义的 属性 'subscribe'。


但是当我尝试在该服务内订阅时它起作用了!!

ps:

我的服务被注入到我的组件的构造函数中(我得到错误的地方)

我的服务有注释:

@Injectable({ 提供于:'root' })

提前致谢

在组件中它不会工作,因为 getPlaces 函数需要 placeID 并且在调用时您不会从组件向函数发送值

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

所以你必须在这里传递 placeID 并通过添加引用来订阅它,就像我写的结果一样。现在,您将获得来自 api.

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

并在服务中将 Observale 添加到函数中

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