[英]ngFor Array not updating DOM view angular 5. Updating dom on 2nd click
I am getting contacts list using contact api. 我正在使用联系人API获取联系人列表。
contacts = new Array<Object>();
public signIn() {
this.getContacts().then((res)=>{
console.log("res",res);
this.contacts =res;
})
}
and here is my html 这是我的html
<button (click)="signIn()">Import google contacts</button>
<div *ngFor="let contact of contacts">
{{contact}}
</div>
The problem is when I click sign in button on first time, the html DOM View is not updated. 问题是,当我第一次单击“登录”按钮时,html DOM视图未更新。 But when I click 2nd time, then it DOM html view is updated.
但是,当我单击第二次时,它将更新DOM html视图。 I want it to be updated on first time.
我希望它是第一次更新。 Can anybody help?
有人可以帮忙吗?
Here is my getContact function. 这是我的getContact函数。 I am using jquery inside.
我在里面使用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);
});
});
})
}
The response I am getting in first time. 我第一次得到的回应。 Following is the screenshot.
以下是屏幕截图。
Just use async
pipe in the view side like this - 就像这样在视图侧使用
async
管道-
<button (click)="signIn()">Import google contacts</button>
<div *ngFor="let contact of contacts | async">
{{contact}}
</div>
public signIn() {
this.contacts = this.getContacts();
}
Also No need to use setTimeout
within your subscription. 另外,无需在订阅中使用
setTimeout
。
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(()=>{
You are recalling the signIn again, don't know why it is required!
您再次想起登录,不知道为什么需要登录! Removing timeout code should bring you out of mess.
删除超时代码会使您一团糟。
this.contacts =res;
this.signIn();
},2000);
this.flag =1;
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.