Javascript 在 Angular 中更改模型后如何更新视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30653190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:31:53  来源:igfitidea点击:

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

javascripttypescriptangular

提问by nicojs

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.

我如何让 Angular 传播我对模型所做的更改。在 AngularJS 中,这真的很容易,但我似乎无法在 Angular 中使用它。我知道整个变化检测系统和视图传播完全改变了。不知何故,我需要通知角度的变化。但我怎么能在实践中做到这一点。

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.

我正在使用 systemjs 0.16,角度 2.0.0-alpha.23。

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

有关示例请参阅此 plnkr(当前,仅适用于 chrome,因为使用了新的“获取”api)

采纳答案by nicojs

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

我发现了这个问题。显然,这是一个在 alpha 27 中要修复的错误。请参阅此错误报告: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().

Angular2 使用 zonejs 来知道何时开始摘要循环(脏检查和更新视图)。截至目前,使用新的 window.fetch() 获取数据后不会触发 zonejs。

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

将 window['fetch'] 行替换为此修复了我的问题: Zone.bindPromiseFn(window['fetch'])('http://jsonplaceholder.typicode.com/users')

回答by James Schermann

To update data at view in AngularJS2 you should use Forms. You can read about this at this pageor see more details here. If I understand Forms correctly, you should modify yout @Viewpart like this:

要在 AngularJS2 中更新视图中的数据,您应该使用Forms。您可以在此页面阅读有关此内容或在此处查看更多详细信息。如果我正确理解表单,您应该像这样修改@View部分:

@View({
    template: `
    <div *for="#user of users" control="users">
        {{user}}
    </div>
    `,
    directives: [For]
})

--edited

--已编辑

Try this:

尝试这个:

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

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

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

    fillUsersAsync(){
        window['fetch']('http://jsonplaceholder.typicode.com/users')
            .then( resp => resp.json())
            .then( users => 
                var usersArr = []
                users.forEach(user => 
                      usersArr.push(user.name))
                this.users = new Control(usersArr));
        }
 }

 bootstrap(App);

I am not sure that my answer is totally correct, but I can't find more information. Experiment with this code and may the Force be with you! :)

我不确定我的回答是否完全正确,但我找不到更多信息。尝试使用此代码,原力与您同在!:)

Also I found this link, veryinformative.

我也找到了这个链接非常有用。

As I understand, when in constructor you should initialize youre usersvariable via new Control(some data)and then, in view template you can access to this data like this - {{users.value}}.

据我了解,在构造函数中时,您应该users通过初始化变量new Control(some data),然后在视图模板中,您可以像这样访问此数据 - {{users.value}}

If it does not work: try the same but with very simple data, e.g. use string instead of an array.

如果它不起作用:尝试相同但非常简单的数据,例如使用字符串而不是数组。

And this videowill helps to unserstand forms in ng2.

该视频将有助于在NG2 unserstand形式。

回答by Alan Wagner

Just answered it here Angular2 View Not Changing After Data Is Updated

刚刚在这里回答了数据更新后 Angular2 视图未更改

Basically, there was a bug in Beta 2.0.0-beta.1.

基本上,Beta 2.0.0-beta.1 中存在一个错误。

Hope it helps!

希望能帮助到你!

回答by shmck

Ng-prefixes are back. Forhas now become ngForfor Angular2 versions alpha-24+.

吴前缀又回来了。For现在已成为ngForAngular2 版本 alpha-24+。

import {NgFor} from 'angular2/directives';
@View({
  directives: [ngFor]
})

Then use *ng-for=#user of users"in the template.

然后*ng-for=#user of users"在模板中使用。

Checkout the ngFor docsor a working example

查看ngFor 文档工作示例