[英]angular 2 router.navigate undefined
Im trying to use navigate.route but keep running into this error: TypeError: undefined is not an object (evaluating 'this.router.navigate') 我正在尝试使用navigation.route但仍然遇到此错误:TypeError:undefined不是对象(正在评估“ this.router.navigate”)
I can't seem to get this working so I was wondering if anyone could point out what I'm doing wrong. 我似乎无法正常工作,所以我想知道是否有人可以指出我做错了什么。 Here is my component, and yes my route is defined as such { path: 'profile', component: Profile }. 这是我的组件,是的,我的路线定义为{路径:“配置文件”,组件:配置文件}。 Its working fine with RouterLink just not in router.navigate. 它与RouterLink的正常工作只是不在router.navigate中。 Thanks! 谢谢!
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');
});
}
}
You should inject Router
dependency in your constructor. 您应该在构造函数中注入Router
依赖项。 Additional thing I would like to suggest is, ds.getAccounts()
service call should moved to ngOnInit
life cycle hook of component. 我想建议的ds.getAccounts()
件事是, 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......
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.