【问题标题】:ngFor Array not updating DOM view angular 5. Updating dom on 2nd clickngFor Array 未更新 DOM 视图角度 5. 在第二次单击时更新 dom
【发布时间】:2018-12-06 05:34:02
【问题描述】:

我正在使用联系人 API 获取联系人列表。

contacts = new Array<Object>();
public signIn() {
    this.getContacts().then((res)=>{
        console.log("res",res);
        this.contacts =res;
    })
}

这是我的html

<button (click)="signIn()">Import google contacts</button>
<div *ngFor="let contact of contacts">
    {{contact}}
</div>

问题是当我第一次点击登录按钮时,html DOM 视图没有更新。但是当我第二次点击时,它的 DOM html 视图就会更新。我希望它在第一时间更新。有人可以帮忙吗?

这是我的 getContact 函数。我在里面使用jquery。

public getContacts():any {
    let config = {
        'client_id': 'xxxx',
        'scope': 'https://www.google.com/m8/feeds'
    };
    return new Promise(resolve=>{
        gapi.auth.authorize(config, ()=> {                
            $.ajax({
                url: 'https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=100',
                dataType: 'jsonp',
                data: gapi.auth.getToken()
            }).done(function(data) {
                resolve(data.feed.entry);

            });
        });
    })
  }

我第一次得到的回应。以下是截图。

【问题讨论】:

  • 列表是否需要一段时间后更新?在您的代码中,使用了 setTimeout()。不需要 setTimeout。
  • 不,这是故意的。它不需要在超时时更新。我会删除它。
  • 分享getContacts()函数代码
  • 现在共享
  • 问题正在编辑中。

标签: javascript html angular angular5


【解决方案1】:

像这样在视图侧使用async管道-

<button (click)="signIn()">Import google contacts</button>
<div *ngFor="let contact of contacts | async">
         {{contact}}
</div>

public signIn() {
        this.contacts = this.getContacts();
    }

也无需在订阅中使用setTimeout

【讨论】:

  • 我在使用管道时遇到了这个错误。 "InvalidPipeArgument: '' 用于管道 'AsyncPipe'"
  • 是的,我将删除 timeout 。它也不起作用
  • 它返回任何。
  • 现在共享
【解决方案2】:
contacts =new   Array<Object>();
    public signIn() {
this is an async request.So, this.contacts populates after you get result from this.getContacts()
        this.getContacts().then((res)=>{
            console.log("res",res);
            this.contacts =res;
            setTimeout(()=>{

你又重新调用了登录,不知道为什么需要它! 删除超时代码应该会让你摆脱混乱。

 this.contacts =res;
                    this.signIn();
                },2000);
                this.flag =1;
            })

        }

【讨论】:

  • 这是故意的。我会删除它。我在这里贴错了。
  • 那应该很棒。您是否尝试删除 setTimeout 块?只是想知道在那之后问题仍然存在。
  • 是的,它存在。我试图通过添加超时来解决它。但这没有帮助
  • 能否请您在第一次点击时告诉我们,该行的日志响应是什么 -> console.log("res",res);第二次点击也是如此。
  • 附上截图
猜你喜欢
  • 1970-01-01
  • 2019-07-11
  • 2015-11-21
  • 1970-01-01
  • 2018-06-17
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
  • 2019-11-05
相关资源
最近更新 更多