【问题标题】:ionic 5 : TypeError: Cannot read property 'subscribe' of undefinedionic 5:TypeError:无法读取未定义的属性“订阅”
【发布时间】:2020-08-05 20:52:46
【问题描述】:

我在 IONIC 5 中有这项服务:


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

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


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

我收到错误:TypeError: Cannot read property 'subscribe' of undefined.


但是当我尝试在服务中订阅时它可以工作!!

ps:

  • 离子 5

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

我的服务被注释了:

@Injectable({ 提供在:“根” })

  • IDE 可视化代码

提前致谢

【问题讨论】:

    标签: angular ionic-framework observable angular8 ionic5


    【解决方案1】:

    在组件中它不起作用,因为 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`)
    }
    

    【讨论】:

    • 对于我拥有的 Id 参数,我只是忘了把它放在这里,另一方面添加了“Observable”,并且我有一个新错误“声明类型既不是”的函数void' 和 'any' 必须返回一个值。”,我认为 this.httpClient.get(..) 返回一个 void(或者至少这是它的想法)
    • 您可以再次分享您创建的服务吗?还在组件中,您是否在构造函数中初始化了服务?构造函数(私有 myService:ServiceClassName)?因为你创建的服务应该在 providers 数组内的 app.module 中声明
    猜你喜欢
    • 1970-01-01
    • 2018-02-13
    • 2019-10-11
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    相关资源
    最近更新 更多