3

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.

1
  • 1
    use new UserModelProvider(); Commented Aug 23, 2018 at 9:18

2 Answers 2

4

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])
Sign up to request clarification or add additional context in comments.

1 Comment

thank you ! the problem was the declaration of users. It works perfectly with push method now.
3

Create an instance of the class before assigning the values,

this.userInfo = new UserModelProvider();

1 Comment

this is correct but there are other problems with your code, see my updated answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.