我的角度应用程序有点问题。在第一页上,我有一个包含所有员工列表的表格和一个“创建新员工”按钮,这会打开一个新表格。表单提交后,请求将发送到数据库,然后返回到开始页面。仅当我单击刷新按钮时才会出现新行。请告诉我,我如何自动重新加载数据?也许,我做错了什么。
以下是我的table.component.html:
的一部分<tr *ngFor="let item of getAllEmployees(); let i = index">
<td>{{i+1}}</td>
<td>{{item.firstName}}</td>
<td>{{item.lastName}}</td>
<td [ngSwitch] = "item.isActive">
<span *ngSwitchCase ="1">Yes</span>
<span *ngSwitchDefault>No</span>
</td>
<td>{{item.depName}}</td>
--------------------------------
这是我的table.component.ts的一部分:
export class TableComponent{
constructor(private model: Model){
}
getAllEmployees(): Employee[]{
return this.model.getAllEmployees();
}
这是我的模特:
@Injectable()
export class Model{
private employees: Employee[] = new Array<Employee>();
private departments: Department[] = new Array<Department>();
constructor(private dataSource: DataSource){
this.dataSource.getEmployeesData().subscribe(data => this.employees = data);
this.dataSource.getDepsData().subscribe(data => this.departments = data);
}
getAllEmployees(): Employee[]{
return this.employees;
}
最后,请求:
export const URL = new InjectionToken("url");
@Injectable() 导出类DataSource {
constructor(private http: Http, @Inject(URL) private url: string){
}
getEmployeesData(): Observable<Employee[]>{
return this.sendRequest(RequestMethod.Get, `${this.url}employeeslist`);
}
还有我的表单组件:
export class FormComponent{
employee: Employee = new Employee();
constructor(private model:Model, private activeRoute: ActivatedRoute,
private router: Router){
this.editing = activeRoute.snapshot.params["mode"] == "edit";
let id = activeRoute.snapshot.params["id"];
if(id != null){
Object.assign(this.employee, this.model.getEmployee(id) || new Employee());
}
}
editing: boolean = false;
submitForm(form: NgForm) {
if (form.valid) {
this.model.saveEmployee(this.employee);
this.router.navigateByUrl('/');
}
}
resetForm() {
this.employee = new Employee();
}
getAllDeps(): Department[]{
return this.model.getAllDeps();
}
}
谢谢!
答案 0 :(得分:0)
可能你的错误在这里:
export class FormComponent{
employee: Employee = new Employee();
constructor(private model:Model, private activeRoute: ActivatedRoute,
private router: Router){
this.editing = activeRoute.snapshot.params["mode"] == "edit";
let id = activeRoute.snapshot.params["id"];
if(id != null){
Object.assign(this.employee, this.model.getEmployee(id) || new Employee());
}
}
editing: boolean = false;
submitForm(form: NgForm) {
if (form.valid) {
this.model.saveEmployee(this.employee);
this.router.navigateByUrl('/');
}
}
resetForm() {
this.employee = new Employee();
}
getAllDeps(): Department[]{
return this.model.getAllDeps();
}
当您收到有效表格时,您将保存该员工,然后使用this.router.navigateByUrl(&#39; /&#39;)重定向到您的主页或索引路线; 可能你不应该这样做并再次调用你的getAllEmployees方法再次检索所有记录