JossephBot
JossephBot

Reputation: 23

I cant use .push in my array with angular? Cannot read property jsonArr of undefined

I am triying yo save data using angular service like this :

   @Injectable()
    export class DataServiceProvider {


    url;
  jsonArr = [];


  constructor(public http: Http) {   
    this.url='assets/data/userProfiles.json';
  }

  getProfiles(){
    return new Promise(resolve => {
      this.http.get(this.url).
      subscribe(data => {
        resolve(data.json());
      }, err => {
        console.log(err);
      });
    });
  }


    proccessProfiles(){
        this.getProfiles().then(
          data=>{
            data[0].companies.forEach(function(cur){
              this.jsonArr.push({
                name: cur.name,
                profile: "company"
              });
            })

            data[1].centers.forEach(function(cur){
              this.jsonArr.push({
                name: cur.name,
                profile: "center"

              });
            })
          }
        )
      }

    }

when i called in my app.component.ts:

I've imported this :

import {DataServiceProvider} from '../providers/data-service/data-service';

and in this function I call:

openPopup(){
    console.log('Openpopup ');
    this.modalCtrl.create(ProfilePage).present();   


    this._ds.proccessProfiles();

  }

It return error :

Cannot read property jsonArr of undefined

Do you someone how can i solve that ?

Thank you

Upvotes: 0

Views: 120

Answers (2)

brk
brk

Reputation: 50291

Try by binding this

proccessProfiles(){
    this.getProfiles().then(
      data=>{
        data[0].companies.forEach(function(cur){
          this.jsonArr.push({
            name: cur.name,
            profile: "company"
          });
        }.bind(this)) // changed here

        data[1].centers.forEach(function(cur){

          this.jsonArr.push({
            name: cur.name,
            profile: "center"

          });
        }.bind(this)) //changed here
      }
    )
  }

Upvotes: 0

Alex Lakatos
Alex Lakatos

Reputation: 253

You are not instantiating that service anywhere. If you want a singleton, you need to add it in the constructor() as one of the parameters, and it gets injected there and retrieves the instance. You can then use this to access it.

constuctor(_ds: DataServiceProvider)

Upvotes: 1

Related Questions