Ad

Angular2 - Changing Model Data Using Promises

- 1 answer

I am experimenting with Angular2 (with no experience of Angular1), I have used data binding successfully, but I now want to add promises into the mix to simulate an async request for data. In the following code, setting newData to an object literal works fine, but setting it to an existing populated object does not work.

After trying this for over a day, I need some help. I'm looking for the simplest way to have my promise return some data and have it update the interpolated value in the template. I've read that zones are sometimes used for this, but at the moment, want to keep this to the bare minimum, to help my understanding (hence I've removed factory classes, interfaces, and dependency injection from the sample code)

I suspect the answer is in this victorsavkin post, but at my current level of understanding, it's beyond me.

http://plnkr.co/edit/amLIZWe5UI9jlvpVGv9V?p=preview

import {Component} from 'angular2/core'
import {MockData} from './mock-data.ts'

@Component({
  selector: 'my-app',
  providers: [],
  template:`
    <h1>
    Hello {{data.name}}
    </h1>`,
  directives: []
})
export class App {
  public data = {}

  constructor() {
    new Promise((response, reject) => {
      setTimeout(function() {
        newData = {name:'Sid'}      //works
        //newData = MockData        //doesn't work
        response(newData)  
      }, 1000)

    })
    .then(response => this.data = response)
  }

}

mock-data.js

exports MockData = {
  name:'Nancy'
}
Ad

Answer

I made these two changes to your plunker to get it to work:

export var MockData = {
  name:'Brian'
}

import {MockData} from '../mock-data.ts'

New plunker.

You also don't have to initialize the data property if you use the Elvis operator (?.):

Hello {{data?.name}}

Then in your component just:

public data;
Ad
source: stackoverflow.com
Ad