为什么observable.subscribe仅适用于构造函数 [英] Why observable.subscribe works only from constructor

查看:194
本文介绍了为什么observable.subscribe仅适用于构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Ionic 3应用程序时,我遇到了一个问题,即当您从 ngOnInit 中的服务订阅 observable 时,将局部变量更新到其中,它不会更新视图。

While working on Ionic 3 app I have faced problem that when you subscribe to observable from service in ngOnInit and update a local variable into it, it does not update the view.

例如
HTML模板
< p> {{myVariable}}< / p>

constructor(myService: MyService) {
}
ngOnInit() {
  this.myService.myObservable.subscribe((data) => {
    this.myVariable = data;
  });
}

但是当你从构造函数做同样的事情时,它就可以工作。

But when you do same thing from constructor, it works.

contructor(myService: MyService) {
  this.myService.myObservable.subscribe((data) => {
    this.myVariable = data;
  });
}

它是一款Ionic 3应用。它包含不同的离子标签。问题是当您在 ngOnInit 中订阅时,视图不会自动更新。您可以在标签之间切换以使其正常工作。但是当您在构造函数中订阅时,无需切换标签即可正常工作。

Its an Ionic 3 app. It contains different Ion Tabs. The problem is that the view is not updated automatically when you subscribe in ngOnInit. You have switch between tabs for it to work. But when you subscribe in constructor it works without needing to switch tab.

知道为什么会发生这种情况。任何提示将不胜感激。谢谢。

Any idea why this is happening. Any hints will be appreciated. Thanks.

推荐答案

使用 private myService

contructor(private myService: MyService) {
  this.myService.myObservable.subscribe((data) => {
    this.myVariable = data;
  });
}

这篇关于为什么observable.subscribe仅适用于构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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