【问题标题】:error using result returned from angular service (undefined)使用从角度服务返回的结果时出错(未定义)
【发布时间】:2018-10-04 18:43:16
【问题描述】:

所以我的 Typescript 类中有两个变量:

private myServiceSubscription: Subscription;
myVar: myDto[] = [];

在 ctor 中:

this.myServiceSubscription = this.deliveryPointService
        .getPostalAddresses()
        .subscribe(result => console.log(result));

我可以在控制台日志中看到服务返回的预期结果(包含两项的列表) 但是,如果我改用另一个订阅:

.subscribe(result => this.myVar);

和(在订阅之外): console.log(this.myVar[0]);

然后我注意到 this.myVar 是未定义的。

为什么 console.log(result) 显示正确的结果,而 this.myVar 却没有?

这是角度 4。

【问题讨论】:

    标签: angular service


    【解决方案1】:

    现在,您不会对服务方法的结果做任何事情。您必须将返回的项目分配给您的变量:

    .subscribe(result => {
       this.myVar = result;
       console.log(this.myVar);
    });
    

    【讨论】:

    • 这就是重点。我想用那个变量做点什么,但如果我按照你说的做,然后在下一个语句中,this.myServiceSubscription ... 之后我想使用 this.myVar,它显示为未定义。好像 myVar 仅在该订阅中具有值?但我需要它在外面,稍后。
    • 你订阅的原因是你正在做的是异步的。如果您在方法返回之前尝试访问 myVar,您将得到 undefined
    • 我尝试在我的方法之后访问它,而不是之前
    • 没关系。异步操作的本质是它不会阻塞执行线程,它不会等待该操作在继续下一行之前完成。看看async programming 在 JS 中是如何工作的
    猜你喜欢
    • 2016-03-20
    • 2020-09-02
    • 2019-10-09
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 2018-03-06
    相关资源
    最近更新 更多