Actualización de la configuración y los datos de la tabla
Aprenda a actualizar la configuración y los datos de la tabla después de enviar el formulario. En esta lección, te asegurarás de que el formulario funcione correctamente y te prepararás para rellenar datos desde las API REST.
Procedimiento
- Enviar el formulario:
- Vaya a la página Crear reserva, introduzca los datos y envíe la reserva. Por ejemplo:

- Después de enviar el formulario, debería aparecer el siguiente mensaje:

- Vaya a la página Crear reserva, introduzca los datos y envíe la reserva. Por ejemplo:
- En un terminal, vaya al directorio src-custom/app/features/create-reservation.
- Ejecute el siguiente comando para generar una tabla que permita a los usuarios ver y actualizar los valores de las reservas.Este comando utiliza los scripts de generación de código IBM que se incluyen en el kit de herramientas para desarrolladores.
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 <nombre de la tabla>,
- --path <ruta donde desea crear la tabla>
- --json-file-path <ruta a buc-table-config.json donde se añadirá la configuración de la tabla>
- --translation-file-path <ruta al archivo JSON de traducción personalizada>
- --extend <nombre de clase de tabla extensible>
ng g @buc/schematics:table-component --help - Después de ejecutar el script, se crean nuevos archivos en la ubicación que especificaste y el ext-search-module.ts archivo se actualiza con un nuevo componente, CreateReservationTableComponent.
- Dado que el componente personalizado que ha generado (
CreateReservationTableComponent) necesita utilizar utilidades y bibliotecas de IBM, mueva el componente al app-customization.impl.ts archivo siguiendo los pasos que se indican a continuación.- Edita el archivo src-custom/app/features/ext-search.module.ts con los siguientes cambios.
- Elimine la instrucción « {CreateReservationTableComponent} ».
- Elimine CreateReservationTableComponent de la
declarationsmatriz.
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @NgModule({ declarations: [ ], imports: [ CommonModule ] }) export class ExtSearchModule { } - Actualiza el archivo src-custom/app/app-customization.impl.ts con los siguientes cambios.
- Añade la siguiente declaración de importación.
import { CreateReservationTableComponent } from './features/create-reservation/create-reservation-table/create-reservation-table.component'; - Añade CreateReservationTableComponent a la matriz de componentes.
static readonly components = [CreateReservationComponent, CreateReservationTableComponent];
- Añade la siguiente declaración de importación.
- Edita el archivo src-custom/app/features/ext-search.module.ts con los siguientes cambios.
- Abre el archivo src-custom/app/features/create-reservation/create-reservation-table/create-reservation-table.component.ts y busca el valor del selector.En este caso, el valor es buc-create-reservation-table. Debe utilizar este valor en el HTML para mostrar la tabla.
- Añade el siguiente código al archivo src-custom/app/features/create-reservation/create-reservation.component.html después del comentario <!–Reservation table -->.
<buc-create-reservation-table [parentPage]="this"></buc-create-reservation-table> - Vuelve al Order Hub de última generación y vuelve a cargar el marco.Vaya a la página Crear reserva para comprobar que se muestra la mesa.

- Observe que el encabezado incluye una casilla de verificación. Para eliminar la casilla de verificación, siga los siguientes pasos.
- Abre el src-custom/app/features/create-reservation/create-reservation-table/create-reservation-table.component.html archivo.
- Añade el siguiente código al final del
<buc-table>elemento.[showSelectionColumn]="false"
- Abre el archivo packages/inventory-search-results/src-custom/assets/custom/buc-table-config.json.
- Reemplaza la matriz de encabezados de create-reservation-table con el siguiente código para actualizar las cadenas del encabezado de la tabla.
Después de reemplazar los encabezados, asegúrate de que el código se vea como el siguiente fragmento.{ "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" }
- Actualiza la sección «Table Headers» (Encabezados de tabla) en el create-reservation-table.component.ts archivo.Observe que los ID coinciden con los buc-table-config.json valores de esta tabla.
/* Table Headers */ public readonly TABLE_HEADERS: any = { TH_NODE_ID: 'nodeId', TH_AVLBL_ON_HAND: 'availableOnHand', TH_TOTAL_RESRV: 'totalReservedQty' }; - Edita el archivo src-custom/app/features/create-reservation/create-reservation-table/create-reservation-table.component.ts con los siguientes cambios.
- Para rellenar la tabla con datos, puede utilizar los parámetros de consulta de buc-table-config.json y algunas variables que Order Hub almacena en el contexto.Añade InventoryContextService y InventoryAvailabilityService como parámetros del constructor.
private ctx: InventoryContextService, private invAvlSvc: InventoryAvailabilityService, private reservationService: CreateReservationService - Añade el ID del inquilino, la declaración de importación y el código:
- Añade la siguiente variable a la
CreateReservationTableComponentclase. Esta variable se utiliza en la llamada a la API.public tenantId; - Añade el siguiente código al método
ngOninit()para rellenar el tenantId:this.tenantId = BucSvcAngularStaticAppInfoFacadeUtil.getInventoryTenantId(); - Añade la declaración de importación correspondiente:
import { BucSvcAngularStaticAppInfoFacadeUtil } from '@buc/svc-angular'; - Añada el siguiente código:
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 []; }) ); }
- Añade la siguiente variable a la
- Prepara la tabla para obtener los datos de las API:
- Reemplaza el
fetchTableData()método por el siguiente código para llamargetReservationa ygetInventoryAvailabilityBreakup: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 mostrar la información en la tabla, debe utilizar la API
getAvailabilityBreakupInventoryexistente ygetReservationla API delinventory-sharedpaquete. Por lo tanto, debe añadir las siguientes declaraciones de importación: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';
- Reemplaza el
- Añade un método de controlador para mostrar notificaciones de éxito o error. Order Hub dispone de servicios para mostrar notificaciones.
- Añadir el
BucNotificationServicecomo parámetro del constructor:private bucNotificationService: BucNotificationService - Añadir el
showNotificationmétodo:// notification showNotification(statusType, message) { const notification = new BucNotificationModel({ statusType, statusContent: message }); this.bucNotificationService.send([notification]); } - Añade la declaración de importación correspondiente:
import { BucNotificationModel, BucNotificationService} from '@buc/common-components';
- Añadir el
- Para rellenar la tabla con datos, puede utilizar los parámetros de consulta de buc-table-config.json y algunas variables que Order Hub almacena en el contexto.
- Añadir un pie de página con las opciones Cancelar y Crear.
- Abre el archivo src-custom/app/features/create-reservation/create-reservation.component.html.
- Reemplaza el código existente
<div class="screen-footer">por el siguiente código.<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> - Actualiza el archivo src-custom/assets/custom/i18n/en.json con las cadenas de traducción para las etiquetas Cancelar y Crear.
"custom": { "LABEL_CREATE_RESERVATION": "Create reservation", "SUCCESS_RESERVATION": "Reservation successful", "ERROR_RESERVATION": "Reservation failed:", "LABEL_CREATE": "Create", "LABEL_CANCEL": "Cancel" },
- Actualiza el archivo src-custom/app/features/create-reservation/create-reservation.component.ts para gestionar las acciones Cancelar y Crear.
- En la clase CreateReservationComponent, declare una nueva variable booleana isCancelled.
public isCancelled: boolean; - En el método constructor, añade el parámetro Router.
private router: Router - Añade los siguientes métodos para gestionar las acciones Cancelar y Crear.
onCancel() { this.isCancelled = true; this.router.navigate([Constants.RESULTS_ROUTE]); } onSave() {} - Añade las siguientes declaraciones de importación.
import { ActivatedRoute, Router } from '@angular/router'; import { Constants } from '@buc/inventory-shared';
- En la clase CreateReservationComponent, declare una nueva variable booleana isCancelled.
- Cree un servicio para llamar a la API Crear reserva desde Sterling™ Intelligent Promising Inventory Visibility para rellenar los datos de disponibilidad.
- Abre el archivo src-custom/app/features/create-reservation/services/create-reservation-service.ts.Actualiza el archivo con el siguiente código para llamar a la API « Sterling Intelligent Promising » (Obtener API de reservas): Inventory Visibility Get Reservation API:
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$; }
- Abre el archivo src-custom/app/features/create-reservation/services/create-reservation-service.ts.
- Si está suscrito a Global Inventory Visibility, abra el archivo src-custom/app/features/create-reservation/create-reservation.component.ts y añada el siguiente código.
- Añade un método de controlador para mostrar notificaciones de éxito o error. Order Hub dispone de servicios para mostrar notificaciones.
- Añadir el BucNotificationService como parámetro del constructor.
private bucNotificationService: BucNotificationService - Añade el método showNotification.
// notification showNotification(statusType, message) { const notification = new BucNotificationModel({ statusType, statusContent: message }); this.bucNotificationService.send([notification]); } - Añade la declaración de importación correspondiente.
import { BucNotificationModel, BucNotificationService} from '@buc/common-components';
- Añadir el BucNotificationService como parámetro del constructor.
- Modifique el método « onSave( » según sea necesario.
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); } }
- Añade un método de controlador para mostrar notificaciones de éxito o error. Order Hub dispone de servicios para mostrar notificaciones.