shotleybuilder
shotleybuilder

Reputation: 123

ng2 display object in html

I'm trying to work out how to display an object in html using angular2. In ng1 I assigned to a variable and double braced the variable name in the html and bingo! Now I can't seem to get any data displayed at all.

Here is my simple method call:

  onSubmit(value: oSearch): void {
    console.log('you submitted value: ', value);
    Meteor.call('methodName',value.type,value.year,value.idNumber, function(error,result) {
      if (error) {
        console.log('failed', error);
      } else {
        this.oResult = result[0];
        console.log('successful call', this.oResult);
      }
    })
  }

The object gets printed to the console. But I cannot get it to render by using:

{{oResult}}

oResult is declared using

oResult:Object;

Completely new to ts and ng2.

Update

Okay, I tried NgZone, but that didn't work. I'm getting behaviour I really don't understand.

} else {      
console.log('successful call', result[0].topItem);
this.oResult = result[0];
console.log('successful call', this.oResult);

Both console.logs print the object correctly but oResult displays as [object Object]

If I change to:

this.oResult.topItem = result[0].topItem

then I get a Meteor error thrown and the 2nd console.log doesn't print. The error is:

Exception in delivering result of invoking 'methodName': TypeError: Cannot set property 'topItem' of undefined

My server method was working perfectly with ng1. I've tried a synchronous version of http but no change in behaviour has resulted.

Perhaps someone knows of a tutorial demo of http method call using updated angular2-meteor that I can fork?

Upvotes: 2

Views: 233

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657366

Angular doesn't recognize the value change if fields are updated by code running outside Angulars zone. Inject zone: NgZone and run the code within zone.run(...). It might also be sufficient to initialize the library within Angular to make it use the async API patched by Angular which notifies Angular about possible changes.

  constructor(private zone: NgZone) {
  }

  onSubmit(value: oSearch): void {
    console.log('you submitted value: ', value);
    Meteor.call('methodName',value.type,value.year,value.idNumber, function(error,result) {
      if (error) {
        console.log('failed', error);
      } else {
        zone.run(function() {
          this.oResult = result[0];
          console.log('successful call', this.oResult);
        });
      }
    });
  }

See also Service events do not affect template correctly for an example.

Upvotes: 0

Related Questions