我有3个选项卡,其中一个选项卡显示一个包含员工列表的表.第一次加载时工作正常.ngOnInit使用http get从服务器获取数据.之后,当我点击添加新员工打开一个表单,该表单从用户那里获取输入,当点击该提交时,我调用一个调用http post服务的函数将该数据发布到我的服务器,在那里它插入记录然后在那之后它被重定向回员工组件,但是现在已经加载了该员工组件,除非我重新编译我的代码,否则我看不到我在表中插入的新记录.
employee.component.ts(加载员工表)
import { Component, OnInit, OnDestroy } from '@angular/core';
import { EmployeeService } from '../employee.service';
@Component({
selector: 'app-employees',
templateUrl: './employees.component.html',
styleUrls: ['./employees.component.css']
})
export class EmployeesComponent implements OnInit {
public employeeObj:any[] = [{emp_id:'',empname:'',joindate:'',salary:''}] ;
constructor(private employeService:EmployeeService) { }
ngOnInit() {
this.employeService.getEmployees().subscribe(res => this.employeeObj = res);
}
}
Run Code Online (Sandbox Code Playgroud)
form.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { EmployeeService } from '../../employee.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css'],
})
export class FormComponent implements OnInit {
empform;
ngOnInit() {
this.empform = new FormGroup({
empname: new FormControl(""),
joindate: new FormControl(""),
salary: new FormControl("")
})
}
constructor(private employeeService: EmployeeService, private router:Router)
{ }
onSubmit = function(user){
this.employeeService.addEmployee(user)
.subscribe(
(response) => { this.router.navigate(['/employees']); }
);
}
}
Run Code Online (Sandbox Code Playgroud)
employee.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
@Injectable()
export class EmployeeService{
constructor(private http:Http){}
addEmployee(empform: any[]){
return this.http.post('MY_API',empform);
}
getEmployees(){
return
this.http.get('MY_API').map((response:Response)=>response.json());
}
}
Run Code Online (Sandbox Code Playgroud)
AppModule.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { EmployeeService } from './employee.service';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { NavComponent } from './nav/nav.component';
import { ContainerComponent } from './container/container.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { EmployeesComponent } from './employees/employees.component';
import { CompaniesComponent } from './companies/companies.component';
import { InternsComponent } from './interns/interns.component';
import { FormComponent } from './employees/form/form.component';
import { ComformComponent } from './companies/comform/comform.component';
import { InternformComponent } from './interns/internform/internform.component';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
NavComponent,
ContainerComponent,
DashboardComponent,
EmployeesComponent,
CompaniesComponent,
InternsComponent,
FormComponent,
ComformComponent,
InternformComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule,
RouterModule.forRoot([
{
path:'dashboard',
component:DashboardComponent
},
{
path:'employees',
component:EmployeesComponent
},
{
path:'companies',
component:CompaniesComponent
},
{
path:'interns',
component:InternsComponent
},
{
path:'addemployee',
component:FormComponent
},
{
path:'comform',
component:ComformComponent
},
{
path:'internform',
component:InternformComponent
}
])
],
providers: [EmployeeService],
bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
问题是我从ngOnInit调用我的API,它在第一次加载组件时完全加载.当我提交表单时,它会转到我的API,然后重定向回员工组件,但数据不会更新.
PS:我很抱歉这么小的帖子.我是这个网站的新手.
更新:
自从我发布这个帖子以来已经有一年多了,我看到很多人都从中受益或者可能没有受益.但是我想指出我已经理解了导致错误的原因,现在我将尝试让您理解解决方案.
这里适应的最重要的概念是角度生命周期钩.发生的是,我们在第一次加载组件时调用ngOnInit,这只会在角度应用程序被引导时触发一次.这类似于类构造函数,但它只触发一次.所以你不应该在这里进行任何与DOM相关的修改.你应该了解Angular Life Cycle Hook来解决这个问题.自从我过去8个月搬到Vuejs后,我没有工作的解决方案,但在一些空闲时间我会在这里发布更新.
请尝试router在employee组件中添加事件。这样,每当/employee路由url状态时,它将获取员工详细信息。
employee.ts组件
constructor(private employeeService: EmployeeService, private router:Router)
{ }
ngOnInit() {
this.router.events.subscribe(
(event: Event) => {
if (event instanceof NavigationEnd) {
this.employeService.getEmployees().subscribe(res => this.employeeObj = res);
}
});
}
Run Code Online (Sandbox Code Playgroud)
作为一般规则,在路由时,角度路由器将尽可能重用组件的相同实例。
因此,例如,从/component/1to导航到/component/2url 映射到相同的组件(但具有不同的参数)将导致路由器在导航到 时实例化 Component 的实例/component/1,然后在导航时重新使用相同的实例到/component/2。根据您所描述的内容( wherengOnInit只被调用一次),似乎这就是您遇到的情况。如果没有看到您的模板和路线配置,就很难确定。我知道您说您的 URL 正在从 更改/employees为/form,但这可能无关紧要,具体取决于您的模板和路由配置的设置方式。如果您愿意,您可以在此处发布该代码(您的模板和路由器配置)以供检查。
除此之外,另一种选择是路由器将其所有事件作为流公开。因此,您可以订阅该流并对其采取行动,而不仅仅是依赖ngOnInit.
在您的 employee.component.ts 中
.....
export class EmployeesComponent implements OnInit {
.....
ngOnInit() {
this.router.events
// every navigation is composed of several events,
// NavigationStart, checks for guards etc
// we don't want to act on all these intermediate events,
// we just care about the navigation as a whole,
// so only focus on the NavigationEnd event
// which is only fired once per router navigation
.filter(e => e instanceof NavigationEnd)
// after each navigation, we want to convert that event to a call to our API
// which is also an Observable
// use switchMap (or mergeMap) when you want to take events from one observable
// and map each event to another observable
.switchMap(e => this.employeeService.getEmployees())
.subscribe(res => this.employeeObj = res);
}
Run Code Online (Sandbox Code Playgroud)
编辑
我看到一段奇怪的代码:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { EmployeeService } from '../../employee.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css'],
})
export class FormComponent implements OnInit {
empform;
ngOnInit() {
this.empform = new FormGroup({
empname: new FormControl(""),
joindate: new FormControl(""),
salary: new FormControl("")
})
}
constructor(private employeeService: EmployeeService, private router:Router) { }
onSubmit(user){ // <-- change this line
this.employeeService.addEmployee(user)
.subscribe(
(response) => { this.router.navigate(['/employees']); }
);
}
}
Run Code Online (Sandbox Code Playgroud)
但总的来说,您是说如果您导航到您的员工组件,然后导航到您的表单组件,然后返回您的员工组件,当您第二次点击员工组件时,您的员工列表不会刷新。
您可以使用console.log语句来确保ngOnInit在上面的屏幕流中多次调用吗?因为,根据您的路由器配置,当您导航到员工列表以形成并返回时,您的员工组件应该重新初始化(通过ngOnInit再次调用)
| 归档时间: |
|
| 查看次数: |
21506 次 |
| 最近记录: |