0

I have a model to store some data. I created a array of that model in my service.Like this

modelArray: MyModel[];

But when i try to push some data to the array it fails with the error

Cannot read property push of undefined

this.modelArray.push(currentData);//THE PROBLEM CODE

I'm not sure about the right approach to doing this.

my service code looks like this:

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { NgAuthService } from '../shared-service/service/ng-auth.service';
import { AppLocalStorageService } from '../shared-service/service/app-local-storage.service';
import { MyModel } from './model/my-model';
@Injectable()
export class ModelService {
    authObj: any;
    appConstants: any;
    baseUrl: any;
    count: any;
    modelArray: MyModel[];

    constructor(private http: Http, public ngAuth: NgAuthService, public localStorage: AppLocalStorageService) {
        this.authObj = this.ngAuth.getNgAuth();
        this.appConstants = this.ngAuth.getAppConstant();
        this.baseUrl = this.authObj.apiServiceBaseUri;
    }
    /*Get data using Api*/
    public getCompanydata(sinceId: any, isBookmarked: any) {

        var Url = this.baseUrl + this.ngAuth.getApiUrl('getdata') +'?bookMarked=false&count=25';
        var authData = JSON.parse(this.localStorage.localStorageGet('authorizationData'));
        var token = 'Bearer ' + authData.token;
        var self = this;

        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        headers.append('Authorization', token);

        return this.http.get( Url, { headers: headers, method: 'GET' })
            .toPromise()
            .then(function (response: any) {
                return response.json();
            })

    }
    /*Set blurbsArray*/
    public setBlurb(data:any) {
        var s = data.dataArray;
        var bArray = [];
        for (let i in s) {
            var currentData = new MyModel();
            currentData.isShareableToFacebook = s[i].isShareableToFacebook;
            currentData.author = s[i].author;
            currentData.publishedDate = s[i].publishedDate;
            currentData.contentSourceType = s[i].contentSourceType;
            currentData.bookMarked = s[i].bookMarked;


             this.modelArray.push(currentData);//THE PROBLEM CODE
        }


    }
    /*return blurbsArray*/
    public getBlurb() {
        return this.modelArray;
    }

    public checkIsPostedToSocial(provider: any, socialData: any) {
        var providerFound = false;

        for (let i in socialData) {
            if (socialData[i].provider == provider) {
                providerFound = true;
                if (socialData[i].posted) {
                    return true;

                }
                else {
                    return false;
                }

            }
        }

        if (!providerFound) {
            return false;
        }
        return true;
    }

    public checkIsScheduledToSocial(provider: any, socialData: any) {
        var providerFound = false;
        console.log(socialData);

        for (let i in socialData) {
            if (socialData[i].provider == provider) {
                providerFound = true;
                if (!socialData[i].posted) {
                    return true;

                }
                else {
                    return false;
                }

            }
        }

        if (!providerFound) {
            return false;
        }
        return true;
    }





}

Though i'm able to assign a array to this model array like below

this.modelArray = bArray;

but not able to push.

Kindly guide if the approach is correct or not Thanks

1
  • what is the error log ? and where is this setBlurb called Commented Sep 19, 2017 at 7:25

1 Answer 1

5

I think you get

Cannot read property push of undefined

You haven't initialized your modelArray. It is currently undefined and you try to call function push on the undefined. With this.modelArray = bArray it works because your bArray is initialized and the reference is assigned to the modelArray which refers to an ready array object.

Make it to refer to an empty array (to refer to something).

modelArray: MyModel[] = [];
Sign up to request clarification or add additional context in comments.

Comments

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.