Angular2 injected Router is undefined

2.1k Views Asked by At

if I inject the router from @angular/router into a component and then use it, I get an error saying the cannot call navigateByUrl of undefined.

This is the component I use the router instance:

import { Component, OnInit } from '@angular/core';
import { UserAccountService } from '../service/user-account.service'
import { Response } from '@angular/http';
import * as jQuery from 'jquery';
import { Router } from '@angular/router';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private userAccountService: UserAccountService,
              private appRouter: Router) { }

  public loginClicked(): void {
    this.userAccountService.Login(this.Email, this.Password).subscribe(this.loginCallback);
  }

  private loginCallback(data: any) {
    if(data.success) {
      localStorage.setItem('access_token', data.token);
      this.appRouter.navigateByUrl('/dashboard'); //-> error
    } else {
      [...]
    }  
  }
}

The routes are defined inside the app module:

const appRoutes: Routes = [
  {  path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [UserAccountService],
  bootstrap: [AppComponent]
})

And inside index.html I define my

Did I forget anything? I have no clue on how to get it working correctly...

1

There are 1 best solutions below

0
On BEST ANSWER

You can use the arrow function to make sure you can still have a reference to this and it is LoginComponent instance:

....subscribe((data) => this.loginCallback(data));

Another option is use bind method like:

....subscribe(this.loginCallback.bind(this));

or in contructor:

this.loginCallback = this.loginCallback.bind(this);

One more option is using arrow function within your loginCallback:

private loginCallback = (data: any) => {
  ...
}