简体   繁体   中英

Angular2 - changing model data using Promises

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'
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM