Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update the view after changing the model in Angular?

How do I let Angular propagate the changes i did to the model. In AngularJS this would be really easy, but i cannot seem to get it working in Angular. I know the entire change detection system and view propagation is changed entirely. Somehow, i need to inform angular of the changes. But how can i do this in practise.

See this piece of typescript code:

import {Component, View, bootstrap, For} from 'angular2/angular2';

// Annotation section
@Component({
    selector: 'app'
})
@View({
    template: `
    <div *for="#user of users">
        {{user}}
    </div>
    `,
    directives: [For]
})
class App {
    users:Array<String>;

    constructor() {
        this.users = [];
        this.fillUsersAsync();
    }

    fillUsersAsync(){
        window['fetch']('http://jsonplaceholder.typicode.com/users')
            .then( resp => resp.json())
            .then( users => users.forEach(user => this.users.push(user.name)))
            .then( () => console.log('Retrieved users and put on the model: ', this.users));
    }
}

bootstrap(App);

You will see that, after the users get loaded into the model, the view doesn't update.

I'm using systemjs 0.16, angular 2.0.0-alpha.23.

See this plnkr for the example (currently, works only in chrome, as the new 'fetch' api is used)

like image 732
nicojs Avatar asked Jun 04 '15 20:06

nicojs


1 Answers

I found the issue. Apparently, its a bug to be fixed in alpha 27. See this bug report: https://github.com/angular/angular/issues/1913

Angular2 uses zonejs to know when to start the digest cycle (the dirty checking and update the view). As of now, zonejs is not triggered after fetching data with the new window.fetch().

Replacing the window['fetch'] line to this fixed the issue for me: Zone.bindPromiseFn(window['fetch'])('http://jsonplaceholder.typicode.com/users')

like image 165
nicojs Avatar answered Oct 06 '22 19:10

nicojs