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...
You can use the arrow function to make sure you can still have a reference to
this
and it isLoginComponent
instance:Another option is use bind method like:
or in contructor:
One more option is using arrow function within your
loginCallback
: