Atualizando a configuração e dados da tabela
Aprenda como atualizar a configuração e os dados da tabela após o formulário ter sido enviado Nesta lição, você assegura que o formulário funcione corretamente e se prepara para preencher dados de APIs REST.
Procedimento
- Envie o formulário:
- acesse a página Criar reserva e insira e envie uma reserva. Por exemplo:

- Depois de enviar o formulário, você deverá ver a seguinte mensagem:

- acesse a página Criar reserva e insira e envie uma reserva. Por exemplo:
- Em um terminal, vá para o diretório src-custom/app/features/create-reservation .
- Execute o comando a seguir para gerar uma tabela para os usuários visualizarem e atualizarem os valores de reserva.Esse comando usa os scripts de geração de códigos da IBM que estão incluídos no kit de ferramentas do desenvolvedor
ng g @buc/schematics:table-component \ --name create-reservation \ --extend ClientSidePaginationBaseTableComponent \ --path packages/inventory-search-results/src-custom/app/features/create-reservation \ --json-file-path packages/inventory-search-results/src-custom/assets/custom \ --translation-file-path packages/inventory-search-results/src-custom/assets/custom/i18n- --name <nome da tabela>,
- --path <caminho para onde você deseja criar a tabela>
- --json-file-path <caminho parabuc-table-config.json onde a configuração da tabela será adicionada>
- --translation-file-path <caminho para o arquivo JSON de tradução personalizada>
- --extend <nome da classe de tabela extensível>
ng g @buc/schematics:table-component --help - Depois de executar o script, novos arquivos serão criados no local especificado e o arquivoext-search-module.ts arquivo é atualizado com um novo componente, CreateReservationTableComponent.
- Como o componente customizado gerado (
CreateReservationTableComponent) precisa usar utilitários e bibliotecas da IBM , mova o componente para o arquivo app-customization.impl.ts concluindo as etapas a seguir.- Editar o arquivo src-custom/app/features/ext-search.module.ts com as mudanças a seguir.
- Exclua a instrução import {CreateReservationTableComponent} .
- Excluir CreateReservationTableComponent de
declarationsvariedade.
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @NgModule({ declarations: [ ], imports: [ CommonModule ] }) export class ExtSearchModule { } - Atualize o arquivo src-custom/app/app-customization.impl.ts com as mudanças a seguir.
- Inclua a seguinte instrução de importação.
import { CreateReservationTableComponent } from './features/create-reservation/create-reservation-table/create-reservation-table.component'; - Adicionar CreateReservationTableComponent para a matriz de componentes.
static readonly components = [CreateReservationComponent, CreateReservationTableComponent];
- Inclua a seguinte instrução de importação.
- Editar o arquivo src-custom/app/features/ext-search.module.ts com as mudanças a seguir.
- Abra o arquivo src-custom/app/features/create-reservation/create-reservation-table/create-reservation-table.component.ts e localize o valor selector .Nesse caso, o valor é buc-create-reservation-table. Deve-se usar esse valor no HTML para exibir a tabela.
- Inclua o seguinte código no arquivo src-custom/app/features/create-reservation/create-reservation.component.html após o comentário <! -Reservation table -->.
<buc-create-reservation-table [parentPage]="this"></buc-create-reservation-table> - Volte para Order Hub e recarregue o quadro.Acesse a página Criar Reserva para verificar se a tabela é exibida

- Observe que o cabeçalho inclui uma caixa de seleção.. Para remover a caixa de seleção, conclua as seguintes etapas.
- Abra o arquivo src-custom/app/features/create-reservation/create-reservation-table/create-reservation-table.component.html .
- Inclua o código a seguir no final do elemento
<buc-table>.[showSelectionColumn]="false"
- Abra o arquivo packages/inventory-search-results/src-custom/assets/custom/buc-table-config.json .
- Substitua a matriz cabeçalhos do criar-reserva-tabelapelo código a seguir para atualizar as sequências de cabeçalhos da tabela
Após substituir os cabeçalhos, assegure-se de que o código seja semelhante ao fragmento a seguir.{ "name": "Node id", "id": "nodeId", "sortKey": "nodeId", "dataBinding": "shipNode" }, { "name": "Available On hand", "id": "availableOnHand", "sortKey": "availableOnHand", "dataBinding": "reservedQuantity" }, { "name": "Reserved Total", "id": "totalReservedQty", "sortKey": "totalReservedQty", "dataBinding": "reservedQuantity" }
- Atualize a seção Cabeçalhos da tabela no arquivo create-reservation-table.component.ts .Observe que os IDs correspondem aos valores buc-table-config.json para essa tabela.
/* Table Headers */ public readonly TABLE_HEADERS: any = { TH_NODE_ID: 'nodeId', TH_AVLBL_ON_HAND: 'availableOnHand', TH_TOTAL_RESRV: 'totalReservedQty' }; - Edite o arquivo src-custom/app/features/create-reservation/create-reservation-table/create-reservation-table.component.ts com as seguintes mudanças.
- Para preencher a tabela com dados, é possível usar os parâmetros de consulta do buc-table-config.json e algumas variáveis que o Order Hub armazena no contexto.Adicione o InventoryContextService e InventoryAvailabilityService como parâmetros do construtor.
private ctx: InventoryContextService, private invAvlSvc: InventoryAvailabilityService, private reservationService: CreateReservationService - Inclua o ID do locatário, a declaração de importação e o código:
- Inclua a seguinte variável na classe
CreateReservationTableComponent. Essa variável é usada na chamada de API.public tenantId; - Adicione o seguinte código ao
ngOninit()método para preencher o tenantId:this.tenantId = BucSvcAngularStaticAppInfoFacadeUtil.getInventoryTenantId(); - Inclua a instrução de importação correspondente:
import { BucSvcAngularStaticAppInfoFacadeUtil } from '@buc/svc-angular'; - Inclua o código a seguir:
getInventoryAvailabilityBreakup() { const searchCriteria = this.ctx.getSearchCriteria(); const item = (this.reservationService.itemData?.itemId) ? [this.reservationService.itemData.itemId] : ['']; const nodes = searchCriteria.filterCriteria.nodes; this.parentPage.nodesIds = nodes; const data = []; return this.invAvlSvc.getAvailabilityBreakupInventory(item, nodes, [], [searchCriteria.operators.uom.value], [searchCriteria.operators.pc.value], searchCriteria.filterCriteria, searchCriteria.operators.org.value, false, '').pipe( map((response: InventoryBreakupResponse) => { response.nodes.forEach(el => { const colD = { breakup: {}, itemId: '', availableOnHand: '', nodeId: '', totalReservedQuantity: '' }; colD.breakup = el.breakup; colD.availableOnHand = response.summary?.availToSell; colD.nodeId = el.nodeId; colD.totalReservedQuantity = el.breakup.totalReservedQuantity; data.push(colD); }); return data; }), catchError(() => { this.multiModel.totalDataLength = 0; return []; }) ); } getReservation() { return this.reservationService.getReservation(this.tenantId, this.reservationService.reservationRef).pipe( catchError(() => { this.multiModel.totalDataLength = 0; return []; }) ); }
- Inclua a seguinte variável na classe
- Prepare a tabela para obter os dados de APIs:
- Substitua o método
fetchTableData()pelo seguinte código para chamargetReservationegetInventoryAvailabilityBreakup:protected fetchTableData(): Observable < any[] > { const observables = []; observables.push(this.getReservation()); observables.push(this.getInventoryAvailabilityBreakup()); return forkJoin(observables).pipe(map((res) => { const reservationResp: any = res[0]; const nodebrkUp: any = res[1]; const rows = reservationResp.map((item: any) => ({ shipNode: item.shipNode, reservedQuantity: item.reservedQuantity, totalOnhandSupplyQuantity: nodebrkUp.map((data) => data.nodeId === item.shipNode ? data.breakup.totalOnhandSupplyQuantity[0] : '') })) return rows; })); } - Para exibir informações na tabela, é necessário usar a API
getAvailabilityBreakupInventorye a APIgetReservationexistentes do pacoteinventory-shared. Portanto, é necessário incluir as instruções de importação a seguir:import { InventoryAvailabilityService, InventoryContextService } from '@buc/inventory-shared'; import { InventoryBreakupResponse } from '@buc/inventory-shared/lib/services/inventory-availability.service'; import { CreateReservationService } from "../services/create-reservation.service"; import { map, catchError } from 'rxjs/operators'; import { forkJoin } from 'rxjs';
- Substitua o método
- Inclua um método manipulador para mostrar notificações de sucesso ou erro. O Order Hub tem serviços para mostrar notificações.
- Inclua o parâmetro
BucNotificationServicecomo construtor:private bucNotificationService: BucNotificationService - Inclua o método
showNotification:// notification showNotification(statusType, message) { const notification = new BucNotificationModel({ statusType, statusContent: message }); this.bucNotificationService.send([notification]); } - Inclua a instrução de importação correspondente:
import { BucNotificationModel, BucNotificationService} from '@buc/common-components';
- Inclua o parâmetro
- Para preencher a tabela com dados, é possível usar os parâmetros de consulta do buc-table-config.json e algumas variáveis que o Order Hub armazena no contexto.
- Inclua um rodapé com opções Cancelar e Criar .
- Abra o arquivo src-custom/app/features/create-reservation/create-reservation.component.html ..
- Substitua o
<div class="screen-footer">existente pelo código a seguir:<div class="screen-footer"> <!-- button row --> <div class="cds--row"> <div class="cds--col"> <buc-button [attr.tid]="'create-rule-cancel'" class="padding-right--1rem" [type]="'secondary'" (click)="onCancel()" [btnSize]="'normal'"> {{ 'custom.LABEL_CANCEL' | translate }} </buc-button> <buc-button id="saveBtn" [attr.tid]="'create-rule-save'" [type]="'primary'" [btnSize]="'normal'" (click)="onSave()"> {{ 'custom.LABEL_CREATE' | translate }} </buc-button> </div> </div> </div> - Atualize o arquivo src-custom/assets/custom/i18n/en.json com sequências de tradução para os rótulos Cancelar e Criar.
"custom": { "LABEL_CREATE_RESERVATION": "Create reservation", "SUCCESS_RESERVATION": "Reservation successful", "ERROR_RESERVATION": "Reservation failed:", "LABEL_CREATE": "Create", "LABEL_CANCEL": "Cancel" },
- Atualize o arquivo src-custom/app/features/create-reservation/create-reservation.component.ts para manipular as ações Cancelar e Criar .
- Em classe CreateReservationComponent, declare uma nova variável booleana isCancelled.
public isCancelled: boolean; - No método construtor , inclua o parâmetro Router.
private router: Router - Inclua os métodos a seguir para manipular as ações Cancelar e Criar .
onCancel() { this.isCancelled = true; this.router.navigate([Constants.RESULTS_ROUTE]); } onSave() {} - Inclua as instruções de importação a seguir:
import { ActivatedRoute, Router } from '@angular/router'; import { Constants } from '@buc/inventory-shared';
- Em classe CreateReservationComponent, declare uma nova variável booleana isCancelled.
- Crie um serviço para chamar a API Criar reserva do Sterling™ Intelligent Promising Inventory Visibility para preencher os dados de disponibilidade.
- Abra o arquivo src-custom/app/features/create-reservation/services/create-reservation-service.ts ..Atualize o arquivo com o código a seguir para chamar a API de obtenção de reserva do Sterling Intelligent Promising Inventory Visibility :
getReservation(tenantId, referenceId = 'REF2'): Observable < any > { if (tenantId === undefined || tenantId === null || tenantId === '') { return throwError(new Error('Missing required parameter: tenantId')); } let path = '/{tenant}/v1/reservations?reference={referenceId}'; path = path.replace('{tenant}', tenantId).replace('{referenceId}', referenceId); const url = this.domain + path; const obsToReturn$ = this.http.post(url, this.resourceDomain, null, this.options); return obsToReturn$; }
- Abra o arquivo src-custom/app/features/create-reservation/services/create-reservation-service.ts ..
- Se você estiver inscrito em Global Inventory Visibility, abra o arquivo src-custom/app/features/create-reservation/create-reservation.component.ts e inclua o código a seguir.
- Inclua um método manipulador para mostrar notificações de sucesso ou erro. O Order Hub tem serviços para mostrar notificações
- Adicione o BucNotificationService como parâmetro do construtor.
private bucNotificationService: BucNotificationService - Inclua o método showNotification ..
// notification showNotification(statusType, message) { const notification = new BucNotificationModel({ statusType, statusContent: message }); this.bucNotificationService.send([notification]); } - Inclua a instrução de importação correspondente.
import { BucNotificationModel, BucNotificationService} from '@buc/common-components';
- Adicione o BucNotificationService como parâmetro do construtor.
- Modifique o onSave() método conforme necessário.
async onSave() { // Call GIV API here try { alert('Call GIV API here'); this.showNotification('success', this.nlsMap['custom.SUCCESS_RESERVATION']); this.router.navigate([Constants.RESULTS_ROUTE]); } catch (error) { this.showNotification('error', this.nlsMap['custom.ERROR_RESERVATION'] + ' ' + error.error_message); } }
- Inclua um método manipulador para mostrar notificações de sucesso ou erro. O Order Hub tem serviços para mostrar notificações