3

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?

3 Answers 3

11

Change

notification : Array<any>;

to

notification : Array<any> = [];
Sign up to request clarification or add additional context in comments.

2 Comments

thx it works for me , but can you tell why i have to do that ? type isn't enought ?
No, type only specifies what kind of values can be stored in this property, but it doesn't hold a value yet. With = [] we initialize it with an empty array that has the .push() method.
0

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);
}

Comments

0

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

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.