【问题标题】:Angular4, update component on route changeAngular,在路由更改时更新组件
【发布时间】: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 返回所需的结果
  • 那么getRowthis.datasource.file 都不会返回异步结果?
  • this.datasource 是对象数组,所以没有异步

标签: javascript angular angular4-router


【解决方案1】:

将您的代码移动到ngOnInit() 方法并检查您是否获得价值。

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

【讨论】:

    【解决方案2】:

    相信你需要定义/初始化位于showRow上方的entity,如:

    const entity = Entity;

    或类似的东西。抱歉,我对 Angular 也很陌生。

    【讨论】:

      【解决方案3】:

      我找到了问题的答案,我只需要像这样将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>
      `,
      

      【讨论】:

        猜你喜欢
        • 2017-09-13
        • 2018-01-05
        • 1970-01-01
        • 2017-07-04
        • 2017-08-19
        • 2017-06-10
        • 2019-06-04
        • 1970-01-01
        • 2020-01-02
        相关资源
        最近更新 更多