简体   繁体   English

Angular2注入的路由器未定义

[英]Angular2 injected Router is undefined

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. 如果将路由器从@ angular / router注入到组件中,然后使用它,则会收到一条错误消息,提示无法调用undefined的navigationByUrl。

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: 路由在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]
})

And inside index.html I define my 在index.html中,我定义了

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 is LoginComponent instance: 您可以使用箭头功能来确保您仍然可以this进行引用,并且它是LoginComponent实例:

....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 : loginCallback一种选择是在您的loginCallback使用箭头功能:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM