角度 2 router.navigate 未定义
Posted
技术标签:
【中文标题】角度 2 router.navigate 未定义【英文标题】:angular 2 router.navigate undefined 【发布时间】:2017-02-08 08:54:20 【问题描述】:我尝试使用 navigate.route 但一直遇到此错误:TypeError: undefined is not an object (evalating 'this.router.navigate')
我似乎无法让这个工作,所以我想知道是否有人能指出我做错了什么。这是我的组件,是的,我的路线被定义为 path: 'profile', component: Profile 。它与 RouterLink 一起工作正常,只是不在 router.navigate 中。谢谢!
import Component, ViewEncapsulation from '@angular/core';
import DataService from '../shared/services/DataService';
import Widget from '../core/widget/widget';
import TablesBackgrid from './tables-backgrid/tables-backgrid';
import DataTableDirectives from 'angular2-datatable/datatable';
import SearchPipe from './pipes/search-pipe';
declare var jQuery: any;
import Router,ActivatedRoute from '@angular/router';
import IAccounts from '../shared/interfaces/IAccounts';
import Profile from '../profile/profile';
import ROUTER_DIRECTIVES from '@angular/router';
const Agents = [];
@Component(
selector: '[account-list]',
template: require('./account-list.html'),
encapsulation: ViewEncapsulation.None,
directives: [Widget,TablesBackgrid, DataTableDirectives,ROUTER_DIRECTIVES],
styles: [require('./account-list.scss')],
pipes: [SearchPipe]
)
export class AccountList
agents: any[];
router:Router;
constructor(ds:DataService)
let test = ds.getAccounts().then(res =>
this.agents = res.agents;
);
loadProfile(id)
this.router.navigate(['/profile']);
ngOnInit(): void
let searchInput = jQuery('#table-search-input, #search-countries');
searchInput
.focus((e) =>
jQuery(e.target).closest('.input-group').addClass('focus');
)
.focusout((e) =>
jQuery(e.target).closest('.input-group').removeClass('focus');
);
【问题讨论】:
【参考方案1】:您应该在构造函数中注入 Router
依赖项。另外我想建议的是,ds.getAccounts()
服务调用应该移动到组件的ngOnInit
生命周期钩子。
constructor(private ds:DataService, router: Router)
this.router = router;
ngOnInit(): void
let test = this.ds.getAccounts().then(res =>
this.agents = res.agents;
);
//....other code here as is......
【讨论】:
以上是关于角度 2 router.navigate 未定义的主要内容,如果未能解决你的问题,请参考以下文章
未在 Router.navigate() 上触发角度变化检测
Protractor Angular 2 失败:未知错误:未定义角度