【发布时间】:2018-02-20 10:46:45
【问题描述】:
当路由改变时如何更新组件。我有这个组件:
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)返回什么?它会返回实体吗?还是一个可观察的?您可以发布该方法的代码吗? -
在 ngOnInit 中执行,它会起作用并确保您的方法 getRow 返回所需的结果
-
那么
getRow和this.datasource.file都不会返回异步结果? -
this.datasource是对象数组,所以没有异步
标签: javascript angular angular4-router