Search code examples
angularangular2-routingangular2-services

Angular2: Cannot read property 'post' of undefined


Below is my postData code. All my get requests are working fine. When I do the post request, I am getting "Cannot read property 'post' of undefined"

@Injectable()
export class UserService {
    constructor(public _http: Http) { }

        postData(id: any) {
        let data = { "jql": id };
                    let body = JSON.stringify(data);
                    console.log(body);
                    return this._http.post('/api/Desk/Tickets/Search', body, { headers: this.getHeaders() })
                        .map((res: Response) => res.json());
    }
}

Calling function

  UserService.prototype.postData(id).subscribe(data=> {
          console.log('In response');
        });

Solution

  • While this works:

    UserService.prototype.postData(id).subscribe(data=> {
              console.log('In response');
            });
    

    You break the "this" reference inside your service and circumvent the Angular dependency injection. You need to inject your service where you are calling it from and use:

    _localServiceInstance.postData(...) instead of UserService.prototype...
    

    Update

    @AJT_82 is right, you have the syntax of your function wrong and that messes up the this reference. It should be:

    legendItemClick: (e) => {
        console.log(this);
        return false;
    }
    

    This is also crazy unreadable. Define the series with the events an empty object:

    series: {
        animation: false,
        point: {
            events: {}
        }
    }
    

    Then after the option declaration or someplace else in your file you can simply assign the event:

    this.options.plotOptions.series.point.events.legendItemClick = function(e) {
        console.log(this);
        return false;
    };
    

    Here is a working version: https://plnkr.co/edit/ZJQeGLbz3OkR3mkpqc7j?p=info