Updating Angular2 variable using Observable

752 views Asked by At

ALERT: Newbie to Angular2 I have the following code:

@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);
    });

  }
}

my alert does pops up, but the view doesnt change in other words, I don't get the "Hello 42" , I still see just "Hello"

2

There are 2 answers

4
AT82 On BEST ANSWER

This should work:

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

  }
3
SeleM On

Here is a plunker , it is working. should point on the object's name by this.name and there is no need for a the function while subscribing.