如果我将路由器从@ angular/router注入到组件中,然后使用它,则会收到一条错误消息,提示无法调用未定义的navigationByUrl.
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: './loginponent.html', styleUrls: ['./loginponent.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] })在index.html中,我定义了我的
And inside index.html I define my
我忘记了什么吗?我对如何使其正常工作一无所知...
Did I forget anything? I have no clue on how to get it working correctly...
推荐答案您可以使用箭头功能来确保仍然可以引用this并且它是LoginComponent实例:
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));或在构造器中:
this.loginCallback = this.loginCallback.bind(this);另一种选择是在loginCallback中使用箭头功能:
One more option is using arrow function within your loginCallback:
private loginCallback = (data: any) => { ... }更多推荐
Angular2注入的路由器未定义
发布评论