P
P
parliament_dev2016-12-30 00:02:55
JavaScript
parliament_dev, 2016-12-30 00:02:55

What is the best way to update data in an Angular2 application?

I have a component with a list of companies and I am loading forms to edit or add to `router-outler`

companies.component.html

    <div class="row">
      <div class="col-md-6">
        <app-company-list></app-company-list>
      </div>
      <div class="col-md-6">
        <router-outlet></router-outlet>
      </div>
    </div>

if I click on some item from the list, then I see a form for creating or editing a company, below is the submit method for forms
company.edit.component

    ...
      onSubmit(){
        if (this.isNew){
          this.companyService.addCompany(this.companyForm.value).subscribe((data) => { 
            this.navigateBack(data.id);
            this.companyService.refresh();
          });
    
        } else {
          this.companyService.editCompany(this.companyForm.value, this.company.id).subscribe((data) => {
            this.companyService.refresh();
            this.navigateBack(this.company.id);
          })
    
        }
      }....

After submit I use this.companyService.refresh(); to update list of companies
below companyService and function to add companies and refresh function use EventEmitter
import { Injectable, EventEmitter } from '@angular/core';
    import { Angular2TokenService } from 'angular2-token';
    import { Company } from './company';
    import { Observable } from 'rxjs/Rx';
    import { Headers, Http, Response } from '@angular/http';
    
    import "rxjs/Rx"
    
    @Injectable()
    export class CompanyService {
      companiesChanged = new EventEmitter();
    
      private company: Company;
      private companies: Company[] = [];
    
      constructor(private tokenService: Angular2TokenService) { }
    
      getCompanies(){
        return this.tokenService.get('companies').map((response: Response) => response.json())
      }
    
      getCompany(companyId: number){
        return this.tokenService.get('companies/' + companyId).map((response: Response) => response.json())
      }
    
      addCompany(company: Company){
        return this.tokenService.post('companies', company).map((response: Response) => response.json())
      }
    
      editCompany(company: Company, companyId: number){
        return this.tokenService.put('companies/' + companyId, company).map((response: Response) => response.json())
      }
    
      deleteCompany(company: Company){
        return this.tokenService.delete('companies/' + company.id).map((response: Response) => response.json())
      }
    
      refresh(){
        this.companiesChanged.emit(true);
      }
    }

below is the companies component code
import { Component, OnInit } from '@angular/core';
    import { CompanyService } from './../company.service';
    import { Company } from './../company';
    
    @Component({
      selector: 'app-company-list',
      templateUrl: './company-list.component.html'
    })
    
    export class CompanyListComponent implements OnInit {
      companies: Company[] = [];
      ownCompanies: Company[] = [];
    
      constructor(private cmpService: CompanyService) { }
    
      ngOnInit() {
        this.getCompanies();
        this.cmpService.companiesChanged.subscribe(
          (data) => {
            this.getCompanies();
          }
        )
      }
   
    
      private getCompanies(){
        this.cmpService.getCompanies().subscribe(data => this.companies = data);
      }
    
    }

also i use `refresh` in another component which find in navbar
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
    import { CompanyService } from './../company.service';
    import { Company } from './../company';
    
    @Component({
      selector: 'app-company-dropdown',
      templateUrl: './company-dropdown.component.html'
    })
    
    export class CompanyDropdownComponent implements OnInit {
      @Output() mainCompanyChanged = new EventEmitter();
    
      companies: Company[] = [];
    
      constructor(private cmpService: CompanyService) { }
    
      ngOnInit() {
        this.getCompanies();
        this.cmpService.companiesChanged.subscribe(
          (data) => {
            this.getCompanies();
          }
        )
      }
    
      private getCompanies(){
        this.cmpService.getCompanies().subscribe(data => this.companies = data);
      }
    }

also I use this.companyService.refresh();`after creating, updating or deleting companies from the list of companies.
Question. Is this a good method to update the list of companies? What confuses me is that if, for example, I had 10 components with companies, then I would have to make 10 get requests to update the list. Is there a more efficient method? And is my approach correct?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Kustikov, 2017-01-19
@art1z

What is the secret meaning of storing two lists of companies in different components?
All logic and data should be only in the service, which itself should run refresh for each update (ideally also with debounce)
constructor() {
this.refresh();
}
add(company) {
if (!company.valid())
return this.invalidResult();
let sub =
this.http.post(this.endpoint, company)
.map(r => r.json())
.do( r => {
this.companies.push(r);
this.loaded.emit(this .companies);
this.refresh();
});
return sub;
}
refresh() {
this.http.get(this.endPoint).debounce(1000)
// map to json()
.subscribe(r => {
this.companies = r;
this.loaded.emit(this.companies);
})
}
Then it subscribes everywhere to loaded and throughout the application you use one and always valid list of companies. Just don't forget to subscribe to add/delete or the requests won't go through.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question