【问题标题】:Calling behaviour of constructor confused me构造函数的调用行为让我感到困惑
【发布时间】:2019-07-11 17:27:19
【问题描述】:

我正在研究 Angular 中的参数化路由,其中​​我陷入了构造函数方法的行为。

我有一个像这样的员工详细信息组件

import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-employeedetail',
  templateUrl: './employeedetail.component.html',
  styleUrls: ['./employeedetail.component.css']
})
export class EmployeedetailComponent implements OnInit {
    eid : number;
    name : string;
    constructor(private rt : ActivatedRoute) {
      this.rt.params.subscribe(e=>{
        this.eid = e["id"];
        this.name = e["name"];
      })
      console.log("called detail constructor"+this.eid);
    }
      ngOnInit(){

      } 

}

employeedetail.component.html 如下所示

<p>employeedetail works!</p>
<span>ID of Employee is {{eid}} and name is {{name}}</span>

<a class="btn btn-primary pull-right" [routerLink]="['/employeedetail',102,'user2']">Next</a>

第一步:

我有一个员工列表窗口,其中有如下员工列表。

<p>list-employee!</p>
<table>
    <tr>
            <th>Name</th>
            <th>Mobile</th>
            <th>Location</th>
            <th>View</th>
    </tr>
    <tr>
        <td>User1</td>
        <td>9696969696</td>
        <td>Pune</td>
        <td><a [routerLink]="['/employeedetail',101,'User1']">View</a></td>
    </tr>
    <tr>
        <td>User2</td>
        <td>8686868686</td>
        <td>Pune</td>
        <td><a [routerLink]="['/employeedetail',102,'User2']">View</a></td>
    </tr>

</table>

当我点击用户 1 查看链接详细信息组件时,也会调用构造函数方法,并且我的 eid 和名称是使用用户 1 详细信息设置的

第 2 步

我在详细页面中添加了一个下一步按钮链接,只是为了检查构造函数在单击下一个链接时的行为,我的 eid 和名称变量随用户 2 详细信息发生变化,但这不应该发生,因为这次没有调用构造函数但变量仍然发生变化(@ 987654324@我添加了这个来检查它是否被调用)

【问题讨论】:

    标签: angular routing


    【解决方案1】:

    发生这种情况是因为路由参数的更改不会重构组件(即EmployeedetailComponent)。神奇的事情真的发生了,因为当你第一次登陆这个页面时,你已经订阅了一个 Observable [i.e.组件] -

    this.rt.params.subscribe(e=>{
            this.eid = e["id"];
            this.name = e["name"];
          })
    

    如果在路由中仅更改路由参数,则 Angular 不会重建组件,而是使用在应用导航到请求的路由时创建的相同组件实例。因为你订阅了params observable,你看到eidname 发生了变化。

    如果路由参数发生变化,则在同一路由上,角度路由器会在 params observable 中发出新的参数值,这将重新评估 params 订阅上的代码 [即在您的代码中eidname 将具有新值]。

    希望它能回答您的问题并消除您的困惑。

    【讨论】:

      【解决方案2】:

      当您通过添加到 params 可观察属性的订阅者接收变量 eidname 的值时,会出现这种行为您注入的 ActivatedRoute 服务。

      在第一个员工的第一次请求中,angular 创建组件并调用他的构造函数。之后,当你点击 Next 按钮时,angular 将重用相同的组件实例,但 ActivatedRoute 服务的 params 属性将发出一个新事件,并带有新路由的新值

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-15
        相关资源
        最近更新 更多