Angular how to load a list first

0

I'd like some help if someone has already used this component: Ng2TableModule} from 'ng2-table / ng2-table'; What happens, I'm trying to come up with the list filled in at the beginning, but it's not working, why, I'm identifying this because it only loads the list in the middle of the way after it has tried to load some stuff Ng2Table and then the list is still empty, it starts to get stuck in some functions, because of that the question is how to load the list before everything without it go ahead without trying to load other things.

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder } from "@angular/forms";
import { BordaService } from "../borda.service";
import { Borda } from "../borda";
import { ActivatedRoute, Router } from '@angular/router';
import { HttpModule } from '@angular/http';
import { ToastrService } from 'ngx-toastr';
import { Ng2TableModule } from 'ng2-table/ng2-table';
import { NgTableComponent, NgTableFilteringDirective, NgTablePagingDirective, NgTableSortingDirective } from 'ng2-table/ng2-table';

@Component({
  selector: 'app-borda-list',
  templateUrl: './borda-list.component.html',
  styleUrls: ['./borda-list.component.css'],
  providers: [BordaService]
})
export class BordaListComponent implements OnInit {
  public rows:Array<any> = [];
  public columns:Array<any> = [
    {title: 'Código', name: 'borda.codigoBorda'},
    {title: 'Borda', name: 'borda.nomeBorda', filtering: {filterString: '', placeholder: 'Filter by name'}},
    {title: 'Descrição', name: 'borda.descricaoBorda'},
    {title: 'Valor', name: 'borda.valorBorda'}
  ];
  public page:number = 1;
  public itemsPerPage:number = 10;
  public maxSize:number = 5;
  public numPages:number = 1;
  public length:number = 0;

  public config:any = {
    paging: true,
    sorting: {columns: this.columns},
    filtering: {filterString: ''},
    className: ['table-striped', 'table-bordered']
  };

  bordas : Borda[];
  private data:Array<any> = this.bordas;

  public constructor(private activatedRoute: ActivatedRoute,
    private router: Router,
    private bordaService: BordaService,
    private toastr: ToastrService) {

    this.getAllBordas();
  }

  public ngOnInit():void {
    this.onChangeTable(this.config);
    this.length = this.bordas.length;
  }

  public changePage(page:any, data:Array<any> = this.data):Array<any> {
    let start = (page.page - 1) * page.itemsPerPage;
    let end = page.itemsPerPage > -1 ? (start + page.itemsPerPage) : data.length;
    return data.slice(start, end);
  }

  public changeSort(data:any, config:any):any {
    if (!config.sorting) {
      return data;
    }

    let columns = this.config.sorting.columns || [];
    let columnName:string = void 0;
    let sort:string = void 0;

    for (let i = 0; i < columns.length; i++) {
      if (columns[i].sort !== '' && columns[i].sort !== false) {
        columnName = columns[i].name;
        sort = columns[i].sort;
      }
    }

    if (!columnName) {
      return data;
    }

    // simple sorting
    return data.sort((previous:any, current:any) => {
      if (previous[columnName] > current[columnName]) {
        return sort === 'desc' ? -1 : 1;
      } else if (previous[columnName] < current[columnName]) {
        return sort === 'asc' ? -1 : 1;
      }
      return 0;
    });
  }

  public changeFilter(data:any, config:any):any {
    let filteredData:Array<any> = data;
    this.columns.forEach((column:any) => {
      if (column.filtering) {
        filteredData = filteredData.filter((item:any) => {
          return item[column.name].match(column.filtering.filterString);
        });
      }
    });

    if (!config.filtering) {
      return filteredData;
    }

    if (config.filtering.columnName) {
      return filteredData.filter((item:any) =>
        item[config.filtering.columnName].match(this.config.filtering.filterString));
    }

    let tempArray:Array<any> = [];
    filteredData.forEach((item:any) => {
      let flag = false;
      this.columns.forEach((column:any) => {
        if (item[column.name].toString().match(this.config.filtering.filterString)) {
          flag = true;
        }
      });
      if (flag) {
        tempArray.push(item);
      }
    });
    filteredData = tempArray;

    return filteredData;
  }

  public onChangeTable(config:any, page:any = {page: this.page, itemsPerPage: this.itemsPerPage}):any {
    if (config.filtering) {
      Object.assign(this.config.filtering, config.filtering);
    }

    if (config.sorting) {
      Object.assign(this.config.sorting, config.sorting);
    }

    let filteredData = this.changeFilter(this.data, this.config);
    let sortedData = this.changeSort(filteredData, this.config);
    this.rows = page && config.paging ? this.changePage(page, sortedData) : sortedData;
    this.length = sortedData.length;
  }

  public onCellClick(data: any): any {
    console.log(data);
  }

  getAllBordas() {
    this.bordaService.findAll()
      .subscribe(
        bordas => {
          this.bordas = bordas;
        }
      );
  }
}

Complete Solution:

import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder } from "@angular/forms";
import { BordaService } from "../borda.service";
import { Borda } from "../borda";
import { ActivatedRoute, Router } from '@angular/router';
import { HttpModule } from '@angular/http';
import { ToastrService } from 'ngx-toastr';
import { PaginationConfig } from 'ng2-bootstrap/pagination/pagination.config';

@Component({
  selector: 'app-borda-list',
  templateUrl: './borda-list.component.html',
  styleUrls: ['./borda-list.component.css'],
  providers: [BordaService, PaginationConfig]
})
export class BordaListComponent {

  public rows:Array<any> = [];

  public columns:Array<any> = [
    {title: 'Código', name: 'codigoBorda'},
    {title: 'Borda', name: 'nomeBorda', filtering: {filterString: '', placeholder: 'Filtrar Pela Borda'}},
    {title: 'Descrição', name: 'descricaoBorda'},
    {title: 'Valor', name: 'valorBorda'},
    {title: 'Ativa', name: 'bordaAtiva'},
    {title: '', name: 'acaoAlterar', sort:false, className: 'accepter-col-action'},
    {title: '', name: 'acaoExcluir', sort:false, className: 'accepter-col-action'}
  ];

  acaoEditar : string = '<button type="button" class="btn btn-warning btn-lg" (click)="editBordaPage(borda)">Editar</button>';
  acaoExcluir : string = '<button type="button" class="btn btn-danger btn-lg" (click)="deleteBorda(borda)">Deletar</button>';

  public page:number = 1;
  public itemsPerPage:number = 10;
  public maxSize:number = 5;
  public numPages:number = 1;
  public length:number = 0;

  public config:any = {
    paging: true,
    sorting: {columns: this.columns},
    filtering: {filterString: ''},
    className: ['table table-striped', 'table-bordered']
  };

  bordas : Borda[] = new Array;
  data: Array<any>;

  //
  codigoBorda : number;
  loginUsuarioParam : string;

  public constructor(private activatedRoute: ActivatedRoute,
    private router: Router,
    private bordaService: BordaService,
    private toastr: ToastrService) {

    this.getAllBordas();
  }

  public changePage(page:any, data:Array<any> = this.data):Array<any> {
    let start = (page.page - 1) * page.itemsPerPage;
    let end = page.itemsPerPage > -1 ? (start + page.itemsPerPage) : data.length;
    return data.slice(start, end);
  }

  public changeSort(data:any, config:any):any {
    if (!config.sorting) {
      return data;
    }

    let columns = this.config.sorting.columns || [];
    let columnName:string = void 0;
    let sort:string = void 0;

    for (let i = 0; i < columns.length; i++) {
      if (columns[i].sort !== '' && columns[i].sort !== false) {
        columnName = columns[i].name;
        sort = columns[i].sort;
      }
    }

    if (!columnName) {
      return data;
    }

    // simple sorting
    return data.sort((previous:any, current:any) => {
      if (previous[columnName] > current[columnName]) {
        return sort === 'desc' ? -1 : 1;
      } else if (previous[columnName] < current[columnName]) {
        return sort === 'asc' ? -1 : 1;
      }
      return 0;
    });
  }

  index : number = 0;

  public changeFilter(data:any, config:any):any {
    let filteredData:Array<any> = data;
    this.columns.forEach((column:any) => {
      if (column.filtering) {
        filteredData = filteredData.filter((item:any) => {
          return item[column.name].match(column.filtering.filterString);
        });
      }
    });

    if (!config.filtering) {
      return filteredData;
    }

    if (config.filtering.columnName) {
      return filteredData.filter((item:any) =>
        item[config.filtering.columnName].match(this.config.filtering.filterString));
    }

    let tempArray:Array<any> = [];
    filteredData.forEach((item:any) => {
      let flag = false;
      this.columns.forEach((column:any) => {
        if (item[column.name].toString().match(this.config.filtering.filterString)) {
          flag = true;
        }
      });
      if (flag) {
        tempArray.push(item);
      }
    });
    filteredData = tempArray;

    return filteredData;
  }

  public onChangeTable(config:any, page:any = {page: this.page, itemsPerPage: this.itemsPerPage}):any {
    if (config.filtering) {
      Object.assign(this.config.filtering, config.filtering);
    }

    if (config.sorting) {
      Object.assign(this.config.sorting, config.sorting);
    }

    let filteredData = this.changeFilter(this.data, this.config);
    let sortedData = this.changeSort(filteredData, this.config);
    this.rows = page && config.paging ? this.changePage(page, sortedData) : sortedData;
    this.length = sortedData.length;
  }

  public onCellClick(data: any): any {

    if (data.column == "acaoAlterar") {
      this.editBordaPage(data.row);
    } else if (data.column == "acaoExcluir") {
      this.deleteBorda(data.row);
    }
  }

  getAllBordas() {
    this.bordaService.findAll()
      .subscribe(
        bordas => {
          this.bordas = bordas;
          for (let borda of this.bordas) {
            borda.acaoAlterar = this.acaoEditar;
            borda.acaoExcluir = this.acaoExcluir
            ;
          }

          this.data = this.bordas;
          this.length = this.bordas.length;
          this.onChangeTable(this.config);
        }
      );
  }

  redirectNewBordaPage() {
    this.router.navigate(['/borda/create']);
  }

  editBordaPage(borda: Borda) {
    if (borda) {
      this.router.navigate(['/borda/edit', borda.codigoBorda]);
    }
  }

  deleteBorda(borda: Borda) {
    if (borda) {
      this.bordaService.deleteBordaById(borda.codigoBorda)
      .subscribe (
        data => {
          if (data.status == 200) {
            this.getAllBordas();
            this.toastr.success("Borda", "Borda Excluída Com Sucesso.");
          }
        },
        error => {
          if (error.status == 0) {
            this.toastr.error("Borda", "Sem Conexão Com O WebService."); 
          } else if (error.status == 500) {
            this.toastr.error("Borda", "Não Foi Possível Deletar O Registro.");
          }
        }
      );
    }
  }
}
    
asked by anonymous 05.02.2018 / 00:56

0 answers