Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Cannot read property 'subscribe' of undefined TypeError: Cannot read property 'subscribe' of undefined

I have tried many propositions on fixing this error here on stackoverflow, but now I just need to ask as I have spent many hours with literally getting nowhere now.

I have this simple Service:

constructor(private http: Http, private tokenResolver: TokenResolver) {}

public getEventHistory(): Observable<heatmapElement[]> {

  this.tokenResolver.getToken(true).subscribe(token => {
    var headers = new Headers();
    headers.append('Authorization', 'Bearer ' + token);
    headers.append('Content-Type', 'application/json');

    this.result = this.http.get(this.restApi, new RequestOptions({headers: headers}))
        .map((res: Response) => res.json());
  });

  return this.result as Observable<heatmapElement[]>;
}

I want to get the data using :

public demoData: heatmapElement[] =[];

getEventHistory(): void {
  this.eventHistoryService.getEventHistory()
                          .subscribe(data => this.demoData = data,);
}

This creates a error that I just cant seem to fix:

EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:5555/app/dashboard/dashboard.html:13:8 caused by: Cannot read property 'subscribe' of undefined TypeError: Cannot read property 'subscribe' of undefined

I would be very grateful for help, thank you

like image 689
jibjapda Avatar asked May 23 '17 07:05

jibjapda


People also ask

How do you fix undefined properties Cannot be read?

To solve the "Cannot read properties of undefined" error, make sure that the DOM element you are accessing exists. The error is often thrown when trying to access a property at a non-existent index after using the getElementsByClassName() method. Copied!

Can not read property Subscribe of undefined?

This issue means that something has been replaced with a mock object and returns a dummy result ( undefined ) instead of observable streams. There is an answer for this error in the section called How to mock observables, if the error has been triggered by a mock service, and its property is of type of undefined .

What is subscribe in angular?

Subscribe() is a method in Angular that connects the observer to observable events. Whenever any change is made in these observable, a code is executed and observes the results or changes using the subscribe method. Subscribe() is a method from the rxjs library, used internally by Angular.

How to fix cannot read property ‘…’ of undefined with angular?

We use arr && arr.length > 0 to make sure arr is defined and it has length bigger than 0. To fix Error: TypeError: Cannot read property ‘…’ of undefined with Angular, we should make sure the variable we’re rendering is defined.

What does TypeError cannot read properties of undefined mean?

TypeError: Cannot read properties of undefined (reading x) Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects.

Why can’t I call a function on an undefined variable?

In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined.

What is the meaning of undefined in JavaScript?

Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined.


Video Answer


2 Answers

Odd as this may be, in my instance, after spending lots of time debugging, it turned out, I was using an Output(@Output) EventEmitter property to handle a custom event, and Angular did not recognize my property or custom event property when passed on a template:

e.g

<custom-component (keydownEvent)="someFunctoin()"></custom-component>

The issue with doing the above is(as far as my issue is concerned) (keydownEvent) is not a valid Event handler, but why the heck does it work in development and not when you've built your project. Even MORE strange, ng build --prod does not issue any errors or warning!

Solution

<custom-component keydown="someFunctoin()"></custom-component>

Where do subscriber/subscription related errors come in?

Well, as you'd imagine, one subscribed to the EventEmitter - so I guess that's where the correlation is

like image 93
Hlawuleka MAS Avatar answered Oct 20 '22 18:10

Hlawuleka MAS


you can't return a result of async call outside its subscribe method.

If you want to return Observable from getEventHistory(), you can change subscribe to map or switchMap.

public getEventHistory(): Observable<heatmapElement[]> {

  return this.tokenResolver.getToken(true).switchMap(token => {
    var headers = new Headers();
    headers.append('Authorization', 'Bearer ' + token);
    headers.append('Content-Type', 'application/json');

    return this.http.get(this.restApi, new RequestOptions({headers: headers}));
  })
  .map((res: Response) => res.json() as heatmapElement[]);
}
like image 23
Pengyy Avatar answered Oct 20 '22 19:10

Pengyy