Angular2注入的路由器未定义

编程入门 行业动态 更新时间:2024-10-27 02:20:20
本文介绍了Angular2注入的路由器未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我将路由器从@ 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注入的路由器未定义

本文发布于:2023-11-22 23:15:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619299.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由器   未定义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!