2017-09-12 90 views
1

如何在路由更改時更新組件。我有這個組件:Angular4,路由更改時更新組件

import { Component, OnInit } from '@angular/core'; 
import { ActivatedRoute } from '@angular/router'; 
import { ListService } from '../list/list.service'; 

@Component({ 
    selector: 'view', 
    template: ` 
    <div *ngIf="!entity"> 
    <p>Select <b (click)="showRow()">row {{entity}}</b>!</p> 
    </div> 
    <div *ngIf="entity"> 

     <p >{{entity.id}}</p> 
     <p >{{entity.name}}</p> 
     <p >{{entity.weight}}</p> 
     <p >{{entity.symbol}}</p> 
    </div> 
    `, 
    styles: [] 
}) 
export class ViewComponent implements OnInit { 

    constructor(
    private route: ActivatedRoute, 
    private service: ListService 
) { 
    this.route.params.subscribe(params => { 
     const id = parseInt(params['id']); 
     if (id) { 
     const entity = this.service.getRow(id); 
     this.entity = entity 
     } 
    }); 
    } 

    entity; 

    showRow() { 
    console.log(this.entity); 
    } 

    ngOnInit() { 
    } 
} 

this.entity內部構造是我所願意的對象,但是當我執行showRow this.entity是不確定的,是我做錯了嗎?我試圖將財產更改爲不同的名稱,並且它沒有按預期工作,如果有人知道如何解決這個問題或指向正確的方向。

編輯:從服務

getRow(id) { 
    console.log(id, 'test'); 
    return this.datasource.find(row => row.id === id);//returns good row 
} 
+0

是什麼'this.service.getRow(ID)'返回?它是否返回實體?還是可觀察?你可以發佈該方法的代碼嗎? – DeborahK

+0

在ngOnInit中執行它,它會工作,並確保您的方法getRow返回所需的結果 – Deshak9

+0

因此'getRow'和'this.datasource.file'都不返回異步結果嗎? – DeborahK

回答

0
的getRow

移動你的代碼ngOnInit()方法和檢查將你獲得價值與否。

ngOnInit() { 
    this.route.params.subscribe(params => { 
    const id = parseInt(params['id']); 
    if (id) { 
     const entity = this.service.getRow(id); 
     this.entity = entity 
    } 
    }); 
} 
+0

已移動並且沒有工作 – Viszman

0

我相信你需要定義/初始化定位上面showRow的entity,如:

const entity = Entity;

或類似的規定。道歉我對角度也很陌生。

0

我找到答案,我的問題,我只是需要把router-outlet模板就像這樣:

.... 
.... 
template: ` 
    <router-outlet> 
    <div *ngIf="row?.id; else elseBlock"> 
    <div> 
     <p>{{row.id}}</p> 
     <p>{{row.name}}</p> 
     <p>{{row.weight}}</p> 
     <p>{{row.symbol}}</p> 
    </div> 
    </div> 
    </router-outlet> 
`, 
相關問題