Árvore de páginas

Versões comparadas

Chave

  • Esta linha foi adicionada.
  • Esta linha foi removida.
  • A formatação mudou.

...

Bloco de código
languagexml
firstline1
titleComponente PO-UI
linenumberstrue
collapsetrue
<po-loading-overlay
  [hidden]="!showLoading">
</po-loading-overlay>

<po-page-detail
  p-title="Detalhe do Idioma"
  [p-breadcrumb]="breadcrumb"
  (p-edit)="editClick()"
  (p-back)="goBackClick()">

  <!-- INICIO CODIGO PERSONALIZAVEL -->

  <po-dynamic-view
    [p-fields]="fields"
    [p-value]="record">
  </po-dynamic-view>

  <!-- FINAL CODIGO PERSONALIZAVEL -->

</po-page-detail

Componente TypeScript (personalization-detail.component.ts)

Bloco de código
languagejs
firstline1
titleComponente TypeScript
linenumberstrue
collapsetrue
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { PoBreadcrumb, PoBreadcrumbItem } from '@po-ui/ng-components';

import { PersonalizationService } from '../personalization.service';

@Component({
  selector: 'app-personalization-detail',
  templateUrl: './personalization-detail.component.html',
  styleUrls: ['./personalization-detail.component.css']
})

export class PersonalizationDetailComponent implements OnInit {
  public static cProg = 'html.aplicativos-eai';

  // definicao das variaveis utilizadas
  public currentId: string;
  public fields: Array<any> = [];
  public record = {};
  public showLoading = false;

  public breadcrumb: PoBreadcrumb = { items: [] };
  public breadcrumbItem: PoBreadcrumbItem;

  // construtor com os servicos necessarios
  constructor(
    private service: PersonalizationService,
    private activatedRoute: ActivatedRoute,
    private route: Router
  ) { }

  // load do componente
  public ngOnInit(): void {
    this.activatedRoute.params.subscribe(pars => {
      this.showLoading = true;
      this.record = {};

      // Carrega o registro pelo ID
      // tslint:disable-next-line:no-string-literal
      this.currentId = pars['id'];

      // ------- BUSCA OS VALORES DOS CAMPOS PERSONALIZADOS DA AREA DE NEGOCIO --------
      // busca os valores dos dados a serem apresentados
      this.service.loadValuesById(this.currentId).subscribe(resp => {
        Object.keys(resp).forEach((key) => this.record[key] = resp[key]);

        // ------- BUSCA OS CAMPOS PERSONALIZADOS DO PROGRAMA --------
        // carrega a lista de campos personalizados somente apos receber os dados a serem apresentados
        this.service.loadMetadata().subscribe(metadata => {
          // tslint:disable-next-line:no-string-literal
          this.fields = metadata['fields'];
          this.showLoading = false;
        });
      });
    });

    this.setBreadcrumb();
  }

  private setBreadcrumb(): void {
    this.breadcrumbItem = { label: 'Home', link: '/' };
    this.breadcrumb.items = this.breadcrumb.items.concat(this.breadcrumbItem);
    this.breadcrumbItem = { label: 'Listagem de Idiomas' , link: '/personalization' };
    this.breadcrumb.items = this.breadcrumb.items.concat(this.breadcrumbItem);
    this.breadcrumbItem = { label: 'Detalhe do Idioma' };
    this.breadcrumb.items = this.breadcrumb.items.concat(this.breadcrumbItem);
  }

  // Redireciona quando clicar no botao Edit
  public editClick(): void {
    this.route.navigate(['/personalization', 'edit', this.currentId]);
  }

  // Redireciona quando clicar no botao Voltar
  public goBackClick(): void {
    this.route.navigate(['/personalization']);
  }
}

...

Bloco de código
languagexml
firstline1
titleComponente PO-UI
linenumberstrue
collapsetrue
<po-loading-overlay
  [hidden]="!showLoading">
</po-loading-overlay>

<po-page-edit
  [p-title]="cTitle"
  [p-breadcrumb]="breadcrumb"
  [p-disable-submit]="formEdit.form.invalid"
  (p-cancel)="cancelClick()"
  (p-save)="saveClick()">

  <po<!-- INICIO CODIGO PERSONALIZAVEL -->

  <po-dynamic-form
    #formEdit
    p-auto-focus="string"
    [p-fields]="fields"
    [p-validate]="validationUrl"
    [p-value]="record">
  </po-dynamic-form>

  <!-- FINAL CODIGO PERSONALIZAVEL -->

</po-page-edit>

Componente TypeScript (personalization-edit.component.ts)

Bloco de código
languagexml
firstline1
titleComponente PO-UI
linenumberstrue
collapsetrue
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { PoBreadcrumb, PoBreadcrumbItem, PoDialogService, PoNotificationService } from '@po-ui/ng-components';

import { PersonalizationService } from './../personalization.service';

@Component({
  selector: 'app-personalization-edit',
  templateUrl: './personalization-edit.component.html',
  styleUrls: ['./personalization-edit.component.css']
})
export class PersonalizationEditComponent implements OnInit {
  // Define as variaveis a serem utilizadas
  public cTitle: string;
  public currentId: string;
  public record = {};
  public fields: Array<any> = [];
  public isUpdate = false;
  public showLoading = false;
  public validationUrl = this.service.getUrlAreaValidation();

  public breadcrumb: PoBreadcrumb = { items: [] };
  public breadcrumbItem: PoBreadcrumbItem;

   // Obtem a referencia do componente HTML
  @ViewChild('formEdit', { static: true })
  formEdit: NgForm;

  // Construtor da classe com os servicos necessarios
  constructor(
    private service: PersonalizationService,
    private activatedRoute: ActivatedRoute,
    private route: Router,
    private poDialog: PoDialogService,
    private poNotification: PoNotificationService
  ) { }

  // Load do componente
  public ngOnInit(): void {
    this.isUpdate = false;
    this.showLoading = true;

    // Carrega o registro pelo ID
    this.activatedRoute.params.subscribe(pars => {
      // tslint:disable-next-line:no-string-literal
      this.currentId = pars['id'];

      // Se nao tiver o ID definido sera um CREATE
      if (this.currentId === undefined) {
        this.isUpdate = false;
        this.cTitle = 'Novo Idioma';
      } else {
        this.isUpdate = true;
        this.cTitle = 'Edição do Idioma';
      }

      // Atualiza o breadcrumb de acordo com o tipo de edicao
      this.setBreadcrumb();

      // Se for uma alteracao, busca o registro a ser alterado
      if (this.isUpdate) {
        // ------- BUSCA OS VALORES DOS CAMPOS PERSONALIZADOS DA AREA DE NEGOCIO --------
        this.service.loadValuesById(this.currentId).subscribe(resp => {
          Object.keys(resp).forEach((key) => this.record[key] = resp[key]);

          // ------- BUSCA OS CAMPOS PERSONALIZADOS DO PROGRAMA --------
          // Em alteracao temos que receber o registro para depois buscar a lista de campos
          this.getMetadata();
        });
      } else {
        // Se for create, pega a lista de campos
        this.getMetadata();
      }
    });
  }

  private setBreadcrumb(): void {
    this.breadcrumbItem = { label: 'Home', action: this.beforeRedirect.bind(this) };
    this.breadcrumb.items = this.breadcrumb.items.concat(this.breadcrumbItem);
    this.breadcrumbItem = { label: 'Listagem de Idiomas', action: this.beforeRedirect.bind(this) };
    this.breadcrumb.items = this.breadcrumb.items.concat(this.breadcrumbItem);
    this.breadcrumbItem = { label: this.cTitle };
    this.breadcrumb.items = this.breadcrumb.items.concat(this.breadcrumbItem);
  }

  // Retorna a lista de campos
  private getMetadata() {
    this.service.loadMetadata().subscribe(metadata => {
        // tslint:disable-next-line:no-string-literal
        this.fields = metadata['fields'];
        this.showLoading = false;
    });
 }

  // Redireciona via breadcrumb
  private beforeRedirect(itemBreadcrumbLabel) {
    if (this.formEdit.valid) {
      this.route.navigate(['/']);
    } else {
      this.poDialog.confirm({
        title: 'Cancelamento de edição',
        message: 'Os dados ainda não foram gravados, confirma redirecinamento ?',
        confirm: () => this.route.navigate(['/'])
      });
    }
  }

  // Grava o registro quando clicado no botao Salvar
  public saveClick(): void {
    this.showLoading = true;
    if (this.isUpdate) {
      // Altera um registro ja existente
      this.service.update(this.currentId, this.record).subscribe(resp => {
        this.poNotification.success('Dados atualizados com sucesso');
        this.showLoading = false;
        this.route.navigate(['/personalization']);
      });
    } else {
      // Cria um registro novo
      this.service.create(this.currentId, this.record).subscribe(resp => {
        this.poNotification.success('Dados criados com sucesso');
        this.showLoading = false;
        this.route.navigate(['/personalization']);
      });
    }
  }

  // Cancela a edicao e redireciona ao clicar no botao Cancelar
  public cancelClick(): void {
    this.poDialog.confirm({
      title: 'Confirmar cancelamento',
      message: 'Voce deseja realmente cancelar a edição?',
      confirm: () => this.route.navigate(['/personalization'])
    });
  }
}

...

Bloco de código
languagexml
firstline1
titleComponente PO-UI
linenumberstrue
collapsetrue
<po-loading-overlay
  [hidden]="!showLoading">
</po-loading-overlay>

<!-- INICIO CODIGO PERSONALIZAVEL -->

<po-page-dynamic-table
  p-auto-router
  p-title="Listagem de Idiomas"
  [p-actions]="actions"
  [p-breadcrumb]="breadcrumb"
  [p-fields]="fields"
  [p-service-api]="serviceApi">
</po-page-dynamic-table>

<!-- FINAL CODIGO PERSONALIZAVEL -->

Componente TypeScript (personalization-list.component.ts)

Bloco de código
languagexml
firstline1
titleComponente PO-UI
linenumberstrue
collapsetrue
import { Component, OnInit } from '@angular/core';
import { PoBreadcrumb, PoBreadcrumbItem } from '@po-ui/ng-components';
import { PoPageDynamicTableActions } from '@po-ui/ng-templates';

import { PersonalizationService } from './../personalization.service';

@Component({
  selector: 'app-personalization-list',
  templateUrl: './personalization-list.component.html',
  styleUrls: ['./personalization-list.component.css']
})
export class PersonalizationListComponent implements OnInit {
  // Definicao das variaveis utilizadas
  public serviceApi: string;
  public fields: Array<any> = [];
  public showLoading = false;

  public literals;

  public readonly actions: PoPageDynamicTableActions = {
    new: '/personalization/create',
    detail: '/personalization/detail/:id',
    edit: '/personalization/edit/:id',
    remove: true
  };

  public breadcrumb: PoBreadcrumb = { items: [] };
  public breadcrumbItem: PoBreadcrumbItem;

  // Construtor da classe
  constructor(
    private service: PersonalizationService
    ) { }

  // Load do componente
  public ngOnInit(): void {
    this.fields = [];
    this.serviceApi = this.service.getUrlArea();
    this.showLoading = true;

    // ------- BUSCA OS CAMPOS PERSONALIZADOS DO PROGRAMA --------
    this.service.loadMetadata().subscribe(metadata => {
      // tslint:disable-next-line:no-string-literal
      this.fields = metadata['fields'];
      this.showLoading = false;
    });

    this.setBreadcrumb();
  }

  private setBreadcrumb(): void {
    this.breadcrumbItem = { label: 'Home', link: '/' };
    this.breadcrumb.items = this.breadcrumb.items.concat(this.breadcrumbItem);
    this.breadcrumbItem = { label: 'Listagem de Idiomas' };
    this.breadcrumb.items = this.breadcrumb.items.concat(this.breadcrumbItem);
  }
}

...

Bloco de código
languagejs
firstline1
titleComponente de serviço
linenumberstrue
collapsetrue
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { PoNotificationService } from '@po-ui/ng-components';

const httpOptions: object = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    // 'Authorization': 'Basic ' + btoa('super:super@123'),
    // 'Access-Control-Allow-Origin': 'http://localhost:4200',
    // 'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers, X-Requested-With',
    // 'returnFormatVersion': '2',
  })
};

@Injectable({
  providedIn: 'root'
})
export class PersonalizationService {
  public progCode = 'html.aplicativos-eai';

  // Endpoint progress do framework para obtencao da lista de campos personalizados
  private urlMetadata = '/api/btb/v1/personalizationView/metadata/';

  // Endpoint progress da area de negocio para obtencao dos valores dos campos personalizados
  private urlArea = '/api/trn/v1/idiomaValues/';

  constructor(
    private http: HttpClient,
    private poNotification: PoNotificationService,
  ) { }


  // ------- BUSCA OS CAMPOS PERSONALIZADOS DO PROGRAMA --------
  public loadMetadata() {
    return this.http.post<any[]>(this.urlMetadata + this.progCode, httpOptions).pipe();
  }

  // ------- BUSCA OS VALORES DOS CAMPOS PERSONALIZADOS DA AREA DE NEGOCIO --------
  public loadValuesById(cId) {
    // tslint:disable-next-line:whitespace
    return this.http.get<any[]>(this.urlArea + 'byid/' + this.progCode + '/' + cId, httpOptions).pipe();
  }

  public loadAllValues() {
    return this.http.get<any[]>(this.urlArea + this.progCode + '/', httpOptions).pipe();
  }

  public create(cId, record) {
    return this.http.post<any[]>(this.urlArea + this.progCode + '/' + cId, record, httpOptions).pipe();
  }

  public update(cId, record) {
    return this.http.put<any[]>(this.urlArea + this.progCode + '/' + cId, record, httpOptions).pipe();
  }

  public getUrlArea(): string {
    return this.urlArea + this.progCode + '/';
  }

  public getUrlAreaValidation(): string {
    return this.urlArea + 'validateForm/' + this.progCode;
  }
}

...