【发布时间】: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