Nacim Idjakirene
Nacim Idjakirene

Reputation: 1931

Angular 2 : cannot read property 'push' of undefined

In my Angular 2 application I have a function :

notification : Array<any>;
......
......
 getNotification () {
     return setTimeout(() => {
         this.AppbankService.notify(this.user.NameId)
     .subscribe(
         (response) => {
             if (response.status === 200) {
             this.notifications.push(response.json());
             console.log(typeof(this.notifications));
              }
             this.getNotification();
         }
     )
     },5000)}

In this function, I get notification from the server every 5 seconds and try to push them to an array, but a have this:

error app.module.ts:104 error : TypeError: Cannot read property 'push' of undefined(…)

Any suggestion?

Upvotes: 3

Views: 9347

Answers (3)

Gadhia Reema
Gadhia Reema

Reputation: 196

I faced the same issue and then discovered that I forgot to initialize my service method itself and its type was set to any.

Upvotes: 0

Arsalan Ahmed Khan
Arsalan Ahmed Khan

Reputation: 436

I had the same issue of push string message and my issue has resolved by below code.

  messages: Array<string> = [];
  add(message: string): void {
    this.messages.push(message);
}

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657406

Change

notification : Array<any>;

to

notification : Array<any> = [];

Upvotes: 11

Related Questions