没有在Subscribe方法外部设置为Subscribe方法内的变量赋值 [英] Assigning Value To Variable Within Subscribe Method is not set outside of the subscribe method

查看:36
本文介绍了没有在Subscribe方法外部设置为Subscribe方法内的变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Subscribe方法之外取值

public ttl_count = 0;
ngOnInit() {
    this.MacService.getAllCouseCount().subscribe((res)=> {
        this.ttl_count = res['count']
    });
}

每当我在SUBSCRIBE函数内console.log(this.ttl_count)时,我就会得到正确的结果,但每当我在SUBSCRIBE函数之外登录时,我就会得到0

推荐答案

这是因为this.MacService.getAllCouseCount().subscribe方法是异步的,在收到this.MacService.getAllCouseCount()

的响应之前,会先执行console.log(this.ttl_count)外部Subscribe方法

您可以使用异步等待或将此this.MacService.getAllCouseCount()转换为承诺。

这篇关于没有在Subscribe方法外部设置为Subscribe方法内的变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆