1

I have a service which has this method:

public register(user, successCallback, errorCallback) {
    const httpHeaders = new HttpHeaders({
      'Content-Type' : 'application/json',
    });

    return this.httpClient.post(`${this.apiURL}/users/register`, user, { observe: 'response', headers: httpHeaders }).subscribe(
        (response) => successCallback(response),
        (error) => errorCallback(error)
    );
  }

I am calling that service method from a component

this.apiService.register(this.user, function(response) {
        this.router.navigateByUrl('/login', { state: { registered: true } })
      }, function(error) {
        console.log(error);
      });

On the line where I call this.router.navigateByUrl I am getting this error:

ERROR TypeError: Cannot read property 'router' of undefined

I understand that this is not defined, but I am not sure what is the proper way of using this within a callback.

Any advice?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Bob
  • 8,392
  • 12
  • 55
  • 96
  • 1
    Replace the `function() {...}` with the fat arrow `() => {...}` that way it binds to *its* lexical environment. – Nicholas K Mar 26 '20 at 17:50

2 Answers2

1

Two ways to solve it:

  • ES6 way : Replace the function() {...} with the fat arrow () => {...} that way it binds to its lexical environment.
  • ES5 way : Use .bind to bind the execution context for this function.

     this.apiService.register(this.user, function(response) {
        this.router.navigateByUrl('/login', { state: { registered: true } })
     }.bind(this), function(error) {
       console.log(error);
     });
    
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
0

Create a reference to "this" outside the callback function.

let outerThis = this;
this.apiService.register(this.user, function(response) {
    outerThis.router.navigateByUrl('/login', { state: { registered: true } })
  }, function(error) {
    console.log(error);
  });
Cristopher Rosales
  • 476
  • 1
  • 4
  • 14