【问题标题】:Unable to store locally with .subscribe method无法使用 .subscribe 方法在本地存储
【发布时间】:2018-03-06 07:15:57
【问题描述】:

我的代码有问题(我可能误解了什么)。

我使用 angular 5,代码如下:

public readZWaveState(zwave_cmd:String):Observable<String>{     
  return this.http
       .get("http://ipAdd/core/api/jeeApi.php?apikey=xxx&type=cmd&id="+zwave_cmd)
       .map(res => res.json());}

我在另一个像这样的文件中订阅了这个方法:

this.the4beesRestService.readZWaveState("xx").subscribe(
        res => {   
            this.l1_state = res;     
        });

这就是问题所在。我可以使用{{l1_state}} 访问 HTML 代码中的值,但我无法在本地访问它。

我使用 console.log(this.l1_state) 尝试过,但它返回 undefined

我认为这是一个范围问题,所以如果有人可以帮助我解决这个问题,那就太好了。

【问题讨论】:

  • 你需要像 l1_state 一样全局声明这个值:string;还要检查你在哪里使用 console.log 来检查你是否需要在 subscribe 中控制这个值。
  • @HrishikeshKale 谢谢。所以我不能在这个过程的后面访问 l1_state (不是在订阅中,而是在每个示例中的另一个函数中)?
  • 确保您的 console.logsubscribe 中作为其异步调用。如果你写在subscribe之外,它将是未定义的。
  • 是的,你可以访问你需要从你的服务方法返回res.json()。
  • 好的,非常感谢!

标签: javascript angular scope observable


【解决方案1】:

使用下面的代码试试:

this.the4beesRestService.readZWaveState("xx").subscribe((res) => {   
            this.l1_state = res;     
            console.log(this.l1_state);
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 2023-02-13
    • 2021-06-26
    • 2015-04-08
    • 1970-01-01
    相关资源
    最近更新 更多