我有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);
}
}
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']); }
);
}
}
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());
}
}
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 { }
问题是我从ngOnInit调用我的API,它在第一次加载组件时完全加载。当我提交表单时,它会转到我的API,然后重定向回员工组件,但数据不会更新。
P.S:我很抱歉这么小的帖子。我是这个网站的新手。更新:
自从我发布这个帖子以来,已经有一年多的时间了,我看到很多人都从中受益或者没有受益。但是我想指出我已经理解了导致错误的原因,现在我将尝试让您理解解决方案。
这里适应的最重要的概念是Angular Life Cycle Hooks。 发生的是,我们在第一次加载组件时调用ngOnInit,这只会在角度应用程序被引导时触发一次。这类似于类构造函数,但它只触发一次。所以你不应该在这里进行任何与DOM相关的修改。你应该了解Angular Life Cycle Hook来解决这个问题。自从我过去8个月搬到Vuejs后,我没有一个可行的解决方案,但在一些空闲时间我会在这里发布更新。
答案 0 :(得分:4)
请尝试在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);
}
});
}
答案 1 :(得分:3)
作为一般规则,在路由时,角度路由器将尽可能重用组件的相同实例。
因此,例如,从/component/1
导航到/component/2
,其中url被映射到相同的组件(但具有不同的参数)将导致路由器在您导航时实例化Component的实例到/component/1
,然后在导航到/component/2
时重复使用该实例。根据您所描述的内容(ngOnInit
仅被调用一次),似乎这就是您遇到的情况。如果没有看到模板和路线配置,很难肯定地说。我知道您说您的网址已从/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);
}
编辑
我看到了一段奇怪的代码:
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']); }
);
}
}
但总的来说,如果您导航到员工组件,然后导航到表单组件,然后再返回到员工组件,那么当您第二次点击员工组件时,您的员工列表不会刷新。 / p>
您是否可以使用console.log
语句确保在您的屏幕流程中多次调用ngOnInit
?因为,根据您的路由器配置,当您导航到员工列表以形成和返回时,应重新初始化您的员工组件(通过再次调用ngOnInit
)
答案 2 :(得分:1)
如果你降级@ angular / router @ 4.1.3似乎在routerLink上工作,如果你导航它会触发ngOnInit
答案 3 :(得分:1)
当您的组件与路径链接时,最好在订阅ActivatedRoute参数的构造函数中添加代码并强制进行更改检测,例如:
constructor(private route: ActivatedRoute, private changeDetector: ChangeDetectorRef) {
super();
this.route.params.subscribe((data) => {
*/update model here/*
this.changeDetector.detectChanges();
}
}
答案 4 :(得分:1)
确保app.component.html内有<route-outlet></route-outlet>
。这应该适用于最新版本的Angular 5。
答案 5 :(得分:1)
我认为发生这种情况是因为您进行异步调用是因为您的路由调用不在Angular生命周期之外?
首先检查您的日志是否显示以下内容:
WARN: 'Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?'
如果是这种情况,解决方案非常简单,则必须告诉Angular在其生命周期内调用您的路由指令。
接下来的代码应该可以解决您的问题:
import { NgZone } from '@angular/core';
import { Router } from '@angular/router';
...
constructor(
private employeeService: EmployeeService,
private router:Router,
private ngZone: NgZone) { }
onSubmit = function(user) {
this.employeeService.addEmployee(user)
.subscribe(
(response) => {
this.ngZone.run(() =>
this.router.navigate(['/employees']));
}
);
}
答案 6 :(得分:0)
1.import要导航的组件
例如import { SampleComponent} from './Sample.component';
2。将组件添加到要导航的构造器中
constructor( private Comp: SampleComponent){}
3。将此代码添加到需要导航的地方
this.Comp.ngOnInit();
this._router.navigate(['/SampleComponent']);--/SampleComponent-your router path
例如,在“员工插入”之后,它会重定向到员工列表页面
this.service.postData(Obj)
.subscribe(data => {
(alert("Inserted Successfully"));
this.Comp.ngOnInit();
this._router.navigate(['/SampleComponent']);
},
error => {
alert(error);
});
答案 7 :(得分:0)
在EmployeesComponent中添加以下行
ionViewWillEnter(){
this.ngOnInit();
}
它将在重定向后手动调用ngOnInit