Angular4,更新路由更改组件

时间:2017-09-12 05:22:14

标签: 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">
    <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

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

3 个答案:

答案 0 :(得分:1)

将代码移至ngOnInit()方法并检查是否有价值。

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

答案 1 :(得分:0)

我认为您需要定义/初始化位于showRow上方的entity,例如:

const entity = Entity;

或类似的东西。道歉我对角度也很新。

答案 2 :(得分: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>
`,
相关问题