0

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 Answers 2

1

This should work:

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

  }
Sign up to request clarification or add additional context in comments.

4 Comments

Okay, it works for me when I tested it, the view changes :)
Forked the plunker provided by 5313M above, and as can see it works :) plnkr.co/edit/Z8bZPzKm0zZ0q4Mcm1g7?p=preview But I see you accepted my answer, so good that you figured it out! :)
ok, this works, thank you, quick question, why this works: source.subscribe(x => {...} but not this: source.subscribe(function (x) {...} ?
Someone smarter can probably answer this better. I only know that with function (x)... you loose the ability of using this, and this.name is what you, in this case, want to use to bind it to your view. Hopefully someone else can explain better...
0

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.

3 Comments

Your example doesnt work, after clicking the button, the "Hello" doesnt change to "Hello 42", its the same issue I am inquiring about.
Ah , Ok it was not clear what you want .. thought it is an issue with observables .. i'll update the answer
@Pacman the plnkr is updated with some cleanups .. (slightly different from AJT_82) & it is working :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.