0
votes

Im trying to use navigate.route but keep running into this error: TypeError: undefined is not an object (evaluating '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. 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');
    });
  }

}
1

1 Answers

1
votes

You should inject Router dependency in your constructor. Additional thing I would like to suggest is, ds.getAccounts() service call should moved to ngOnInit life cycle hook of component.

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......
}