【问题标题】:Updating Angular2 variable using Observable使用 Observable 更新 Angular2 变量
【发布时间】:2016-12-30 01:46:15
【问题描述】:

警告:Angular2 的新手 我有以下代码:

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
            <button (click)="ClickMe()">Button</button>`
})

export class AppComponent
{
  name:string;
  ClickMe(event : event) :void {
    var source = new Observable((observer: any) => {
      observer.next(42);
    });
    source.subscribe(function (x : any) {
    name = x;
    alert(x);
    });

  }
}

我的警报确实弹出,但视图没有改变,换句话说,我没有得到 "Hello 42" ,我仍然只看到 "Hello"

【问题讨论】:

    标签: angular angular2-observables


    【解决方案1】:

    这应该可行:

      ClickMe(event : Event) :void {
        var source = new Observable((observer: any) => {
          observer.next(42);
        });
        source.subscribe(x => {
        this.name = x;
        alert(x);
        });
    
      }
    

    【讨论】:

    • 好的,当我测试它时它对我有用,视图改变了:)
    • 对上面 5313M 提供的 plunker 进行了分叉,并且可以看到它有效 :) plnkr.co/edit/Z8bZPzKm0zZ0q4Mcm1g7?p=preview 但我看到你接受了我的回答,太好了,你想通了! :)
    • 好的,这有效,谢谢,快速提问,为什么有效:source.subscribe(x => {...} 但不是这个:source.subscribe(function (x) {.. .} ?
    • 更聪明的人可能会更好地回答这个问题。我只知道使用function (x)... 你失去了使用this 的能力,而this.name 是你在这种情况下想要用来将它绑定到你的视图的。希望其他人能解释得更好...
    【解决方案2】:

    这是一个 plunker ,它正在工作。 应该通过this.name 指向对象的名称,并且在订阅时不需要function

    【讨论】:

    • 您的示例不起作用,单击按钮后,“Hello”不会变为“Hello 42”,这与我询问的问题相同。
    • 啊,好吧,不清楚你想要什么..认为这是可观察的问题..我会更新答案
    • @Pacman plnkr 更新了一些清理..(与 AJT_82 略有不同)并且它正在工作:-)
    猜你喜欢
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    相关资源
    最近更新 更多