【发布时间】: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@我添加了这个来检查它是否被调用)
【问题讨论】: