在router.navigate之后未调用Angular 4 ngOnInit [英] Angular 4 ngOnInit not called after router.navigate

查看:107
本文介绍了在router.navigate之后未调用Angular 4 ngOnInit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个标签,其中一个标签显示一张包含员工列表的表格.第一次加载时效果很好.ngOnInit使用http get从服务器获取数据.之后,当我单击添加新员工"以打开一个表单时,该表单将接受用户的输入,然后单击该提交时,我调用一个函数,该函数调用http发布服务以将该数据发布到我的服务器上,并在其中插入记录,然后它被重定向回员工组件,但是现在已经加载了员工组件,除非重新编译代码,否则我看不到插入表中的新记录.

I have 3 tabs in which one tab shows a table with list of employees. Works good when it is loaded the first time.ngOnInit Fetches data from server using http get. After that when I click add new employee to open a form, which take input from user and when that submit is clicked I call a function which calls the http post service to post that data to my server where it inserts the records and then after that it is redirected back to employee component, but now that employee component was already loaded, I cannot see the new record that I inserted in table unless I recompile my code.

employee.component.ts(加载员工表)

employee.component.ts ( Which loads the employee Table)

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

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

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,然后将其重定向回员工组件,但数据并不会得到应有的更新.

The problem is I am calling my API from ngOnInit which loads perfectly the first time the component loads. When I submit the form it goes to my API and then it is redirected back to the employee component, but the data is not updated as it should.

P.S:对这么小的帖子,我感到抱歉.我是这个网站的新手.

P.S : I am sorry for such small post. I am kind of new to this website.

更新:

自从我发布此主题以来已经一年多了,我看到很多人都从中受益,也许没有.但是,我想指出的是,我已经了解了导致错误的原因,现在我将尽力使您理解该解决方案.

It has been more than a year now since I posted this thread and I see a lot of people have benefit from it or maybe not. However I would like to point that I have already understood what caused the error and I will now try to make you understand the solution.

此处最重要的概念是Angular 生命周期挂钩. 发生的是,我们在第一次加载组件时调用ngOnInit,并且只有在启动角度应用程序时才会触发一次.这类似于类构造函数,但仅触发一次.因此,您不应在此处进行任何与DOM相关的修改.您应该了解Angular Life Cycle Hooks来解决此问题.自从过去8个月移居到Vuejs以来,我没有可用的解决方案,但是有空的时候我会在这里发布更新.

The most important concept to adapt here is the Angular Life Cycle Hooks. What happens is, we call ngOnInit the first time a component is loaded and this will only fire once when the angular application is bootstrapped. This is similar to a class constructor but it only fires once. So you should not put any DOM related modifications here. You should understand Angular Life Cycle Hooks to solve this problem. I do not have a working solution with me as I moved to Vuejs since last 8 months but in some free time I will post an update here.

推荐答案

请尝试在employee组件中添加router事件.这样,每当路由/employee url状态时,它将获取员工详细信息.

Please try adding router event in employee component. So that every time when /employee url state is routed it will fetch the employee details.

employee.ts组件

employee.ts component

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);
           }
    });
}

这篇关于在router.navigate之后未调用Angular 4 ngOnInit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆