【发布时间】:2017-10-09 13:56:58
【问题描述】:
我正在使用 nodejs 和 angular 2 开发一个简单的项目。 在我的客户项目中,我有一个包含表单和提交事件的组件。当我抛出此事件时,表单中的所有数据都会正确发送到我的节点应用程序。 但是我有另一个组件,它有一个表,我在其中列出了位于我的数据库中的所有寄存器。
一切正常。但是我应该在提交提交后同时加载我的表格。 我不知道我该怎么做。
我尝试实现这样的东西:
export class EmployeeListComponent implements OnInit {
public employees: string[];
constructor(private employeeService : EmployeeService) {
this.employeeService.employeeRequest().subscribe(employees => {
this.employees = employees;
})
}
ngOnInit() {
}
}
在我的注册组件中我做了这个方法:
onRegister(){
const Employee = {
name : this.name,
familyName: this.familyName,
participation: this.participation
}
if (!this.validateService.validateRegister(Employee)){
this.alertMsg = JSON.stringify({'msg': 'All fields must be filled'});
console.log(this.alertMsg);
return false;
} else {
this.registerService.employeeRegister(Employee).subscribe(data => {
this.alertMsg = JSON.stringify({'msg': 'Employee registered successfully'});
console.log(this.alertMsg);
return this.router.navigate(['/list']);
});
};
};
我的测试表明我的代码工作正常,但我的表格在第一次提交时加载正确。之后,我必须手动刷新浏览器以再次加载我的表格。 有没有人知道我做错了什么或者可以告诉我一些编码方法?
【问题讨论】:
-
您可以调用召回您的
employeeRequest()来重新填充this.employees = employees;,而不是进行页面刷新 -
嗨@LLai 谢谢你的回答。但只是另一个问题。如果您再次看到我的代码,我会在构造函数中调用employeeRequest()。我对客户端有所了解,并且知道每个组件在构造函数的生命周期中都有你的生命周期。那么你如何建议我可以在哪里召回我的employeeRequest?
-
您可以将调用移动到它自己的方法中。然后从构造函数和
employeeRegister().subscribe的成功回调中调用它。作为旁注,我会将您的 api 调用移至 ngOnit 方法而不是构造函数。保持构造函数精简并将逻辑移至 ngOnInit 通常更安全。这是因为 Angular 在调用 ngOnit 时进行控制。
标签: javascript node.js forms angular