Javascript Angular4,在路线变更时更新组件
如何在管线更改时更新组件。我有这个部分:Javascript Angular4,在路线变更时更新组件,javascript,angular,angular4-router,Javascript,Angular,Angular4 Router,如何在管线更改时更新组件。我有这个部分: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { ListService } from '../list/list.service'; @Component({ selector: 'view', template: ` <div *ngIf="!entity"&
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() {
}
}
将代码移动到
ngOnInit()
方法,然后检查是否获得值
ngOnInit() {
this.route.params.subscribe(params => {
const id = parseInt(params['id']);
if (id) {
const entity = this.service.getRow(id);
this.entity = entity
}
});
}
我认为您需要定义/初始化位于showRow上方的
实体
,例如:
const entity=entity代码>
或者类似的东西。抱歉,我对angular也很陌生。我找到了问题的答案,我只需要将路由器插座
放在模板中,就像这样:
....
....
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>
`,
。。。。
....
模板:`
{{row.id}}
{{row.name}
{{row.weight}}
{{row.symbol}}
`,
this.service.getRow(id)
返回什么?它是否返回实体?还是可以观察到的?您可以发布该方法的代码吗?在ngOnInit中执行该操作,它将起作用并确保您的方法getRow返回所需的结果,因此既不getRow
也不this.datasource.file
返回异步结果?this.datasource
是对象数组,因此没有异步
....
....
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>
`,