Search code examples
javascriptajaxangularscopingsubscribe

this.<servicename> not available inside error function in angular2


I have a strange error in angular2. while the following code works fine

loginResult.subscribe(
      (data) =>
        this.response = data,
      (err) =>

        this._ajaxService.handleError(err, 'A string to summarize the activity')
    );

The following code says cannot read property handleError of undefined. This happens only in case of a failed request.

    loginResult.subscribe(
   function (response) {

        this.response = response;
        console.log(this.response);

      },
      function (error) {

        this._ajaxService.handleError(error, 'A string to summarize the activity')

      }
    );

Solution

  • Bind "this" to both success and failure functions.

    loginResult.subscribe(
        function (response) {
            this.response = response;
            console.log(this.response);
        }.bind(this), // <== "this" binding here
        function (error) {
            this._ajaxService.handleError(error, 'A string to summarize the activity')
        }.bind(this)
    );