2016-09-29 97 views
0

我試着使用navigate.route但繼續運行這個錯誤:類型錯誤:未定義不是對象(評估「this.router.navigate」)角2 router.navigate未定義

我似乎無法得到這個工作,所以我想知道是否有人可以指出我做錯了什麼。這是我的組件,是的,我的路由被定義爲這樣{路徑:'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...... 
}