【问题标题】:Angular2 injected Router is undefinedAngular2注入的路由器未定义
【发布时间】:2016-12-17 12:51:48
【问题描述】:

如果我将路由器从@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 {
      [...]
    }  
  }
}

路由在应用模块内部定义:

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 中我定义了我的

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

【问题讨论】:

  • 你在哪里打电话loginCallback?我想这里的上下文非常重要
  • 好的,添加上下文时我注意到我在 userAccountsService 中引用了 loginCallback 和 this。

标签: angular typescript router


【解决方案1】:

您可以使用箭头函数确保您仍然可以引用this,它是LoginComponent 实例:

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

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

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

或在构造函数中:

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

另一种选择是在您的loginCallback 中使用箭头功能:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 2021-11-28
    相关资源
    最近更新 更多