注入Angular2的路由器未定义

时间:2016-12-17 03:15:34

标签: angular typescript router

如果我将路由器从@ angular / router注入一个组件然后使用它,我会收到一个错误,说不能调用未定义的navigateByUrl。

这是我使用路由器实例的组件:

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 {
      [...]
    }  
  }
}

路线在app模块中定义:

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]
})

在index.html中我定义了我的     

我忘了什么吗?我不清楚如何让它正常工作......

1 个答案:

答案 0 :(得分:2)

您可以使用箭头功能确保您仍然可以引用this并且LoginComponent实例:

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

另一个选择是使用绑定方法,如:

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

或在contructor中:

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

还有一个选项是在loginCallback中使用箭头功能:

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