1

Here is my code :

@Component({
    selector: "foo",
    template: `
      <span>Init : {{o.init}}</span>
      <span>Loaded data : {{o.loadedData}}</span>
    `,
    providers: [
        Services
    ]
})
export class FooComponent implements OnInit{
   constructor (private _services: Services) {}

   o: Object
   ngOnInit() {
      o = {"init": "foo"}
      this.services.randomCall()
          .subscribe(
              res => this.o["loadedData"] = res["loadedData"]  
          )
   }
}

So o.loadedData doesn't appear everytime due to a race condition between my randomCall() and the template rendering. What I would like would be to notify angular after having assigned o["loadedData"] = res["loadedData"]. In angular1, I would have done a call to the scope's digest() function.

How can I do something similar in angular2 ?

Thanks !

Edit: I added back this, it was a typo.

Scipion
  • 11,449
  • 19
  • 74
  • 139

2 Answers2

4

I would use the this keyword:

o: Object
ngOnInit() {
  this.o = {"init": "foo"}; // <-----

  this.services.randomCall()
      .subscribe(
          res => {
            this.o["loadedData"] = res["loadedData"]; // <-----
          }
      );
 }

Edit

You could force Angular2 to detect changes using the ChangeDetectorRef class, this way:

constructor(private cdr:ChangeDetectorRef) {
}

o: Object
ngOnInit() {
  this.o = {"init": "foo"};

  this.services.randomCall()
      .subscribe(
          res => {
            this.o["loadedData"] = res["loadedData"];
            this.cdr.detectChanges(); // <-----
          }
      );
 }
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
2

Normally this is done by Angulars change detection which gets notified by its zone that change detection should happen. When code that somehow runs outside Angulars zone modifies your model, then you can invoke change detection manually like

export class FooComponent implements OnInit{
   constructor (private _services: Services, private cdRef:ChangeDetectorRef) {}

   o: Object
   ngOnInit() {
      o = {"init": "foo"}
      this.services.randomCall()
          .subscribe(
              res => {
                  o["loadedData"] = res["loadedData"];
                  this.cdRef.detectChanges();
              });
          )
   }
}

Because of the missing this as mentioned by Thierry, manual change detection won't help you in this case anyway.

For more options how to invoke change detection see Triggering Angular2 change detection manually

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567