user7430961
user7430961

Reputation: 35

Add new object to array angular

I'm trying to put a JSON object into an array after an API call.

First I made my API call and then I try to add every user into in a formatted JSON object.

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

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.

I certainly don't understand the class, can you help me?

Thank you.

Upvotes: 3

Views: 6590

Answers (2)

danday74
danday74

Reputation: 56986

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:

this.users = [...this.users, this.userInfo]

or in ES5:

this.users = this.users.concat([this.userInfo])

Upvotes: 4

Sajeetharan
Sajeetharan

Reputation: 222582

Create an instance of the class before assigning the values,

this.userInfo = new UserModelProvider();

Upvotes: 3

Related Questions