Update component in angular 2

I am new to angular 2 and trying to learn more about it.

My question is here: How to update a component (call ngOnInit again) .

This component will call the API to retrieve some data from the database. and if you click the button, the PUT request will be sent to the API to update the data in the database. Since the change occurs in the database instead of the component itself, I do not think that ngOnChange or another validation method will work . Here I am trying to call ngOnInit again so that the component can receive updated data.

I tried the nagivate router to refresh this page, but this will not work.

All HTTP methods occur in another utility file, I will not display them here, since this is not relevant.

app.module.ts

@NgModule({ imports: [ RouterModule.forRoot([{path: 'data', component: DataComponent}]); ] }) 

data.component.ts

 @Component({ template: ` <button (click)= "onclick()">Click Me</button> `, .... }); export class DataComponent implements OnInit{ fetchData(): void{ this.dataService.dataSessions().subscribe( data => this.data= data, error=> console.error(error), ()=> {} ); } onclick(){ this.dataChangeService.updateData().subscribe( response=> console.log(response)); this.router.navigate['/data']; } ngOnInit(): void{ this.fetchData(); } 

Any answer would be appreciated, I am always happy to know more.

+6
source share
2 answers

Try calling this.fetchData () method as soon as your call to the server is resolved. Sort of:

 response=> { this.fetchData() ... 
+2
source
  import { Component, OnInit, Inject,OnChanges } from "@angular/core"; import { ProductService } from '../../services/product.service'; import 'rxjs/Rx'; import { ActivatedRoute, Router,NavigationEnd } from '@angular/router' import { JQ_TOKEN } from '../../common/index' @Component({ selector: 'product-list', templateUrl: 'app/store/product_list/product-list.component.html', styleUrls: ['app/store/product_list/css/style.css'] }) export class ProductListComponent implements OnInit { products:any productcount : any sub:any; constructor(private productService:ProductService,private route:ActivatedRoute,@Inject(JQ_TOKEN) private $:any,private router:Router ) { } ngOnInit() { this.productService.getProduct(this.route.snapshot.params['productcategory']).map(product=>this.products) this.products = this.route.snapshot.data['products'] this.productcount=+this.products.length; this.sub = this.route.params.subscribe(params => { this.paramsChanged(params['productcategory']); }); } paramsChanged(productcategory:string) { this.products = this.route.snapshot.data['products'] this.productcount=+this.products.length; console.log('product list paramsChanged' + productcategory); this.router.navigate['/store/'+productcategory]; } } 
-3
source

Source: https://habr.com/ru/post/1013312/


All Articles