[英]Add new object to array angular
I'm trying to put a JSON object into an array after an API call. 我试图在API调用后将JSON对象放入数组中。
First I made my API call and then I try to add every user into in a formatted JSON object. 首先,我进行了API调用,然后尝试将每个用户添加到格式化的JSON对象中。
connectionProvider.ts connectionProvider.ts
import { UserModelProvider } from './../user-model/user-model';
import { MSAdal, AuthenticationContext, AuthenticationResult } from '@ionic-native/ms-adal';
export class MsConnectionProvider {
userInfo : UserModelProvider;
users: UserModelProvider[];
constructor(...) {}
getUserInfo(){
let header = new Headers({
Authorization: this.accessToken;
});
let options = new RequestOptions({headers: header});
this.usersSubscription = this.http.get("https://graph.microsoft.com/v1.0/groups/**ID**/members", options).map(res => res.json()['value']);
this.usersSubscription.subscribe(res => {
for (let user of res){
this.addUserInfo(user.displayName, user.jobTitle, "something", user.mail);
}
});
}
addUserInfo(name, job, departement, mail){
this.userInfo = new UserModelProvider;
this.userInfo.name = name;
this.userInfo.job = job;
this.userInfo.departement = departement;
this.userInfo.mail = mail;
this.users.push(this.userInfo);
}
}
userModelProvider.ts userModelProvider.ts
export class UserModelProvider {
name: string;
job: string;
departement: string;
mail: string;
photo: any;
}
The problem is when I try to push "this.userInfo = new UserModelProvider" into this.users array the function block and nothing happens. 问题是当我尝试将“this.userInfo = new UserModelProvider”推入this.users数组时,功能块没有任何反应。
I certainly don't understand the class, can you help me? 我当然不懂课,你能帮助我吗?
Thank you. 谢谢。
在分配值之前创建类的实例,
this.userInfo = new UserModelProvider();
You can't push to an array that has not been initialised. 您无法推送到尚未初始化的阵列。
you need to change: 你需要改变:
users: UserModelProvider[]
to: 至:
users: UserModelProvider[] = [];
Also (may or may not help): 另外(可能有也可能没有帮助):
Nothing is probably happening because push mutates the array and as such angular change detection may not kick in. 没有什么可能发生,因为推动变异数组,因此角度变化检测可能不会启动。
Instead of using push, create a new array with: 而不是使用push,创建一个新的数组:
this.users = [...this.users, this.userInfo]
or in ES5: 或者在ES5中:
this.users = this.users.concat([this.userInfo])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.