如何在路由更改時更新組件。我有這個組件: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
}
是什麼'this.service.getRow(ID)'返回?它是否返回實體?還是可觀察?你可以發佈該方法的代碼嗎? – DeborahK
在ngOnInit中執行它,它會工作,並確保您的方法getRow返回所需的結果 – Deshak9
因此'getRow'和'this.datasource.file'都不返回異步結果嗎? – DeborahK