4

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...

2
  • Where are you calling loginCallback? I guess context is very important here Commented Dec 17, 2016 at 3:18
  • ok, when adding the context I noticed I refer loginCallback and this inside the the userAccountsService. Commented Dec 17, 2016 at 3:51

1 Answer 1

4

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) => {
  ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.