简体   繁体   中英

how to push data to array of a model in angular2

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

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[] = [];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM