2016-09-29 21 views
0

イム:例外TypeError:未定義のオブジェクトではありません(「this.router.navigate」を評価)角度2 router.navigate未定義

私は、ように見えることはできませんこれは私が間違っていることを誰かが指摘できるかどうか疑問に思っていました。ここに私のコンポーネントがあります。私のルートは{path: 'profile'、component:Profile}として定義されています。 router.navigateではなく、RouterLinkでうまく動作します。ありがとう!

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