ya funciona, lo que veo es que primero carga el dtatable y leugo los datos, tengo un…
- User
ya funciona, lo que veo es que primero carga el dtatable y leugo los datos, tengo un service que se conecta a spring boot y quiero listar desde base de datos, pero utilizando la algoica de ajax o angular proporciona algo mejor? quiero la misma logica, primeroque se cargue la datatable y luego los datos, como puedo hacer eso? este es mi servecio producto - import { HttpClient, HttpErrorResponse } from ‘@angular/common/http’; import { Injectable } from ‘@angular/core’; import { catchError, Observable, throwError } from ‘rxjs’; import { Producto } from ‘…/…/models/producto.model’; import { Categoria } from ‘…/…/models/categoria.model’;
@Injectable({ providedIn: ‘root’ }) export class ProductoService {
private apiUrl = ‘http://localhost:8095/producto’;
constructor(private http: HttpClient) { }
private handleError(error: HttpErrorResponse) { console.error(‘Ocurrió un error:’, error); return throwError(() => new Error('Error: ')); }
listarProductos(): Observable<Producto[]> { return this.http.get<Producto[]>(${this.apiUrl}/listar, { withCredentials: true }) .pipe( catchError(this.handleError), ); } - no uses el simbolo de dolar porque hace que tengas errores, mejor usa SDOLAR cuando quieras usar ese simbolo, este es el componente que funciona actualmente con el listado de ajax que me diste, - import { Component, OnInit } from ‘@angular/core’; import { Config } from ‘datatables.net’;
@Component({ selector: ‘app-producto-listar’, templateUrl: ‘./producto-listar.component.html’, styleUrl: ‘./producto-listar.component.css’ }) export class ProductoListarComponent implements OnInit {
dtOptions: Config = {};
ngOnInit(): void { this.dtOptions = { ajax: ‘assets/data/data.json’, columns: [{ title: ‘ID’, data: ‘id’ }, { title: ‘First name’, data: ‘firstName’ }, { title: ‘Last name’, data: ‘lastName’ }] }; }
}
- uso ajax? o angular proporciona algo mejor? quiero que sea algo sencillo - este es el data json que use como ejemplo { "data": [ { "id": 1, "firstName": "John", "lastName": "Doe" }, { "id": 2, "firstName": "Anna", "lastName": "Smith" }, { "id": 3, "firstName": "Peter", "lastName": "Jones" } ]
} - esta es mi tabla productos de bd create table producto ( idproducto int primary key auto_increment, fecha date not null, nombre varchar(25) not null unique, preciocompra double not null, precioventa double not null, imagen varchar(255), activo int not null, idcategoria int not null, foreign key (idcategoria) references categoria(idcategoria) ); - angular proporciona algo mejor que ajax? - no uses por nada el simbolo de dolar porque tienes errores, en su lugar usa SDOLAR
- Assistant
Para lograr lo que deseas, puedes usar las capacidades nativas de Angular junto con un módulo muy popular llamado Angular DataTables para integrar DataTables con Angular y cargar los datos mediante una llamada HTTP sin necesidad de usar AJAX puro, teniendo así una implementación más limpia y mantenible.
Paso a paso:
-
Instalar Angular DataTables:
npm install angular-datatables npm install jquery datatables.net --save -
Actualizar tu servicio
ProductoService:
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { Producto } from '../../models/producto.model'; @Injectable({ providedIn: 'root', }) export class ProductoService { private apiUrl = 'http://localhost:8095/producto'; constructor(private http: HttpClient) {} private handleError(error: HttpErrorResponse) { console.error('Ocurrió un error:', error); return throwError(() => new Error('Error: ')); } listarProductos(): Observable<Producto[]> { return this.http.get<Producto[]>(`${this.apiUrl}/listar`, { withCredentials: true }).pipe( catchError(this.handleError) ); } }- Actualizar tu componente
ProductoListarComponent:
import { Component, OnInit } from '@angular/core'; import { Subject } from 'rxjs'; import { ProductoService } from '../../services/producto.service'; import { Producto } from '../../models/producto.model'; import { DataTableDirective } from 'angular-datatables'; @Component({ selector: 'app-producto-listar', templateUrl: './producto-listar.component.html', styleUrls: ['./producto-listar.component.css'], }) export class ProductoListarComponent implements OnInit { dtOptions: any = {}; dtTrigger: Subject<any> = new Subject<any>(); productos: Producto[] = []; constructor(private productoService: ProductoService) {} ngOnInit(): void { this.dtOptions = { pagingType: 'full_numbers', pageLength: 10, processing: true, }; this.productoService.listarProductos().subscribe((data: Producto[]) => { this.productos = data; this.dtTrigger.next(); }); } ngOnDestroy(): void { this.dtTrigger.unsubscribe(); } }- Actualizar la plantilla de tu componente (
producto-listar.component.html):
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover"> <thead> <tr> <th>ID</th> <th>Fecha</th> <th>Nombre</th> <th>Precio Compra</th> <th>Precio Venta</th> <th>Imagen</th> <th>Activo</th> <th>Categoría</th> </tr> </thead> <tbody> <tr *ngFor="let producto of productos"> <td>{{ producto.idproducto }}</td> <td>{{ producto.fecha }}</td> <td>{{ producto.nombre }}</td> <td>{{ producto.preciocompra }}</td> <td>{{ producto.precioventa }}</td> <td>{{ producto.imagen }}</td> <td>{{ producto.activo }}</td> <td>{{ producto.idcategoria }}</td> </tr> </tbody> </table>- Instalar jQuery-DataTables en el proyecto:
- En
angular.json, asegúrate de agregar los scripts y estilos necesarios:... "styles": [ "node_modules/datatables.net-dt/css/jquery.dataTables.css", "src/styles.css" ], "scripts": [ "node_modules/jquery/dist/jquery.min.js", "node_modules/datatables.net/js/jquery.dataTables.min.js" ] ...
- En
Con estos cambios, tu componente debería inicializar la tabla y luego llenar los datos obtenidos desde el servicio
ProductoServiceuna vez que la llamada HTTP haya terminado. Angular DataTables hará que el proceso sea más fluido y simple de manejar en comparación con el uso de AJAX puro. -
- User
sale este error al lsitar - producto.service.ts:17 Ocurrió un error: HttpErrorResponse {headers: _HttpHeaders, status: 404, statusText: 'OK', url: 'http://localhost:8095/producto/listar', ok: false, …} handleError @ producto.service.ts:17 (anonymous) @ catchError.js:10 OperatorSubscriber2._this._error @ OperatorSubscriber.js:25 Subscriber2.error @ Subscriber.js:43 Subscriber2._error @ Subscriber.js:67 Subscriber2.error @ Subscriber.js:43 Subscriber2._error @ Subscriber.js:67 Subscriber2.error @ Subscriber.js:43 Subscriber2._error @ Subscriber.js:67 Subscriber2.error @ Subscriber.js:43 Subscriber2._error @ Subscriber.js:67 Subscriber2.error @ Subscriber.js:43 onLoad @ http.mjs:2289 invokeTask @ zone.js:398 (anonymous) @ core.mjs:14556 onInvokeTask @ core.mjs:14556 invokeTask @ zone.js:397 onInvokeTask @ core.mjs:14869 invokeTask @ zone.js:397 runTask @ zone.js:158 invokeTask @ zone.js:479 invokeTask @ zone.js:1109 globalCallback @ zone.js:1152 globalZoneAwareCallback @ zone.js:1173 Zone - XMLHttpRequest.addEventListener:load (async) onScheduleTask @ core.mjs:14550 scheduleTask @ zone.js:378 onScheduleTask @ zone.js:267 scheduleTask @ zone.js:378 scheduleTask @ zone.js:201 scheduleEventTask @ zone.js:227 (anonymous) @ zone.js:1470 (anonymous) @ http.mjs:2364 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:14 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ innerFrom.js:51 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ finalize.js:5 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ finalize.js:5 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 doInnerSub @ mergeInternals.js:19 outerNext @ mergeInternals.js:14 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ innerFrom.js:51 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 mergeInternals @ mergeInternals.js:53 (anonymous) @ mergeMap.js:14 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ filter.js:6 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ map.js:6 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ catchError.js:9 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 ngOnInit @ producto-listar.component.ts:44 callHookInternal @ core.mjs:5136 callHook @ core.mjs:5163 callHooks @ core.mjs:5118 executeInitAndCheckHooks @ core.mjs:5068 refreshView @ core.mjs:12806 detectChangesInView1 @ core.mjs:13015 detectChangesInViewIfAttached @ core.mjs:12978 detectChangesInComponent @ core.mjs:12967 detectChangesInChildComponents @ core.mjs:13028 refreshView @ core.mjs:12841 detectChangesInView$1 @ core.mjs:13015 detectChangesInViewWhileDirty @ core.mjs:12732 detectChangesInternal @ core.mjs:12714 detectChangesInView @ core.mjs:31734 detectChangesInViewIfRequired @ core.mjs:31707 detectChangesInAttachedViews @ core.mjs:31562 _tick @ core.mjs:31532 tick @ core.mjs:31521 (anonymous) @ core.mjs:31902 invoke @ zone.js:365 onInvoke @ core.mjs:14882 invoke @ zone.js:364 run @ zone.js:111 run @ core.mjs:14733 next @ core.mjs:31901 ConsumerObserver2.next @ Subscriber.js:96 Subscriber2._next @ Subscriber.js:63 Subscriber2.next @ Subscriber.js:34 (anonymous) @ Subject.js:41 errorContext @ errorContext.js:19 Subject2.next @ Subject.js:31 emit @ core.mjs:6845 checkStable @ core.mjs:14801 onHasTask @ core.mjs:14899 hasTask @ zone.js:418 _updateTaskCount @ zone.js:439 _updateTaskCount @ zone.js:260 runTask @ zone.js:175 drainMicroTaskQueue @ zone.js:577 Promise.then (async) nativeScheduleMicroTask @ zone.js:553 scheduleMicroTask @ zone.js:564 scheduleTask @ zone.js:387 onScheduleTask @ core.mjs:14551 scheduleTask @ zone.js:378 onScheduleTask @ zone.js:267 scheduleTask @ zone.js:378 scheduleTask @ zone.js:201 scheduleMicroTask @ zone.js:221 scheduleResolveOrReject @ zone.js:2488 resolvePromise @ zone.js:2422 (anonymous) @ zone.js:2330 (anonymous) @ zone.js:2346 Promise.then (async) (anonymous) @ zone.js:2740 ZoneAwarePromise @ zone.js:2662 Ctor.then @ zone.js:2739 loadChildren @ app-routing.module.ts:15 loadChildren @ router.mjs:4311 loadChildren @ router.mjs:4272 (anonymous) @ router.mjs:3927 doInnerSub @ mergeInternals.js:19 outerNext @ mergeInternals.js:14 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ innerFrom.js:51 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 mergeInternals @ mergeInternals.js:53 (anonymous) @ mergeMap.js:14 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:14 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ map.js:7 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ map.js:7 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ tap.js:18 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ switchMap.js:14 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ take.js:12 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ filter.js:6 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ map.js:7 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ combineLatest.js:47 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ mergeInternals.js:25 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ take.js:12 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ innerFrom.js:51 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ take.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 doInnerSub @ mergeInternals.js:19 outerNext @ mergeInternals.js:14 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ innerFrom.js:51 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 mergeInternals @ mergeInternals.js:53 (anonymous) @ mergeMap.js:14 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ startWith.js:11 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ combineLatest.js:40 maybeSchedule @ combineLatest.js:67 _loop_1 @ combineLatest.js:37 (anonymous) @ combineLatest.js:57 maybeSchedule @ combineLatest.js:67 (anonymous) @ combineLatest.js:31 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ map.js:6 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ filter.js:6 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ take.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:14 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ innerFrom.js:51 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ tap.js:15 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ map.js:6 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ map.js:6 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ catchError.js:9 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 doInnerSub @ mergeInternals.js:19 outerNext @ mergeInternals.js:14 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ innerFrom.js:51 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 mergeInternals @ mergeInternals.js:53 (anonymous) @ mergeMap.js:14 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ filter.js:6 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ take.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ throwIfEmpty.js:8 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ catchError.js:9 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ map.js:6 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 doInnerSub @ mergeInternals.js:19 outerNext @ mergeInternals.js:14 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ innerFrom.js:51 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 Zone - Promise.then (async) onScheduleTask @ core.mjs:14550 scheduleTask @ zone.js:378 onScheduleTask @ zone.js:267 scheduleTask @ zone.js:378 scheduleTask @ zone.js:201 scheduleMicroTask @ zone.js:221 scheduleResolveOrReject @ zone.js:2488 then @ zone.js:2693 (anonymous) @ innerFrom.js:59 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:14 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ innerFrom.js:51 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 mergeInternals @ mergeInternals.js:53 (anonymous) @ mergeMap.js:14 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ tap.js:15 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:14 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ innerFrom.js:51 Observable2._trySubscribe @ Observable.js:38 (anonymous) @ Observable.js:32 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ tap.js:15 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ map.js:6 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 mergeInternals @ mergeInternals.js:53 (anonymous) @ mergeMap.js:14 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ tap.js:15 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ filter.js:6 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ map.js:6 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ tap.js:15 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ map.js:6 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ take.js:10 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ tap.js:15 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ takeUntil.js:8 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ finalize.js:5 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ catchError.js:9 (anonymous) @ lift.js:10 (anonymous) @ Observable.js:27 errorContext @ errorContext.js:19 Observable2.subscribe @ Observable.js:23 (anonymous) @ switchMap.js:14 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ map.js:7 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ filter.js:6 OperatorSubscriber2._this._next @ OperatorSubscriber.js:15 Subscriber2.next @ Subscriber.js:34 (anonymous) @ Subject.js:41 errorContext @ errorContext.js:19 Subject2.next @ Subject.js:31 BehaviorSubject2.next @ BehaviorSubject.js:31 handleNavigationRequest @ router.mjs:4536 scheduleNavigation @ router.mjs:5759 navigateToSyncWithBrowser @ router.mjs:5471 initialNavigation @ router.mjs:5419 (anonymous) @ router.mjs:6906 (anonymous) @ core.mjs:31612 _loadComponent @ core.mjs:31612 bootstrap @ core.mjs:31503 (anonymous) @ core.mjs:32312 _moduleDoBootstrap @ core.mjs:32312 (anonymous) @ core.mjs:32282 invoke @ zone.js:365 onInvoke @ core.mjs:14882 invoke @ zone.js:364 run @ zone.js:111 (anonymous) @ zone.js:2498 invokeTask @ zone.js:398 (anonymous) @ core.mjs:14556 onInvokeTask @ core.mjs:14556 invokeTask @ zone.js:397 onInvokeTask @ core.mjs:14869 invokeTask @ zone.js:397 runTask @ zone.js:158 drainMicroTaskQueue @ zone.js:577 Zone - Promise.then (async) onScheduleTask @ core.mjs:14550 scheduleTask @ zone.js:378 onScheduleTask @ zone.js:267 scheduleTask @ zone.js:378 scheduleTask @ zone.js:201 scheduleMicroTask @ zone.js:221 scheduleResolveOrReject @ zone.js:2488 then @ zone.js:2693 (anonymous) @ core.mjs:32278 _callAndReportToErrorHandler @ core.mjs:31275 (anonymous) @ core.mjs:32275 invoke @ zone.js:365 onInvoke @ core.mjs:14882 invoke @ zone.js:364 run @ zone.js:111 run @ core.mjs:14733 bootstrapModuleFactory @ core.mjs:32254 (anonymous) @ core.mjs:32307 invoke @ zone.js:365 run @ zone.js:111 (anonymous) @ zone.js:2498 invokeTask @ zone.js:398 runTask @ zone.js:158 drainMicroTaskQueue @ zone.js:577 Promise.then (async) nativeScheduleMicroTask @ zone.js:553 scheduleMicroTask @ zone.js:564 scheduleTask @ zone.js:387 scheduleTask @ zone.js:201 scheduleMicroTask @ zone.js:221 scheduleResolveOrReject @ zone.js:2488 then @ zone.js:2693 bootstrapModule @ core.mjs:32307 (anonymous) @ main.ts:6 Show 548 more frames Show less producto-listar.component.ts:44 ERROR Error: Error: at producto.service.ts:18:29 at Observable2.init [as _subscribe] (throwError.js:5:64) at Observable2._trySubscribe (Observable.js:38:25) at Observable.js:32:31 at errorContext (errorContext.js:19:9) at Observable2.subscribe (Observable.js:23:9) at catchError.js:14:31 at OperatorSubscriber2._this._error (OperatorSubscriber.js:25:21) at Subscriber2.error (Subscriber.js:43:18) at Subscriber2._error (Subscriber.js:67:30)
- Assistant
El error
404indica que la URL solicitada no se encontró en el servidor. Esto puede deberse a varias razones, como que el endpoint no esté correctamente definido en el backend de Spring Boot o que la URL en Angular no esté bien construida.Para resolver este problema, verifica los siguientes puntos:
Verificar el Endpoint en el Backend (Spring Boot)
Asegúrate de que el endpoint en tu controlador de Spring Boot esté definido correctamente. Por ejemplo:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/producto") public class ProductoController { @Autowired private ProductoService productoService; @GetMapping("/listar") public List<Producto> listarProductos() { return productoService.listarProductos(); } }Asegúrate de que el puerto del servidor de Spring Boot sea el correcto (
8095en este caso) y que el endpoint/producto/listaresté bien definido y no tenga errores ortográficos.Verificar la configuración en Angular
Asegúrate de que la URL en tu servicio de Angular esté correctamente construida y no tenga errores tipográficos. Revisa especialmente cómo has definido la URL base (
apiUrl) y asegúrate de que el URL endpoint coincida con el definido en Spring Boot:import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { Producto } from '../../models/producto.model'; @Injectable({ providedIn: 'root' }) export class ProductoService { private apiUrl = 'http://localhost:8095/producto'; // Asegúrate de que esta URL sea correcta constructor(private http: HttpClient) {} private handleError(error: HttpErrorResponse) { console.error('Ocurrió un error:', error); return throwError(() => new Error('Error: ')); } listarProductos(): Observable<Producto[]> { return this.http.get<Producto[]>(`${this.apiUrl}/listar`, { withCredentials: true }).pipe( catchError(this.handleError) ); } }Asegúrate de que
localhost:8095/producto/listarsea accesible y de que el servidor de Spring Boot esté corriendo y no tenga errores al iniciarse.Probar la URL directamente en el navegador o Postman
Para confirmar que el problema no está en el servidor, intenta acceder al endpoint directamente en tu navegador o en una herramienta de pruebas como Postman:
http://localhost:8095/producto/listarSi esto retorna un
404, el problema está en el backend y necesitarás verificar tu configuración de Spring Boot.Verificar el CORS (Cross-Origin Resource Sharing)
Si estás haciendo la solicitud desde una aplicación Angular que corre en un servidor diferente al de Spring Boot, asegúrate de que el servidor de Spring Boot esté configurado para permitir peticiones CORS:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:4200") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true); } }Resumen
- Verifica que el endpoint en el controlador de Spring Boot esté correctamente definido.
- Confirma que el puerto del servidor de backend (
8095) esté correcto. - Asegúrate de que la URL en el servicio de Angular esté bien construida.
- Prueba el endpoint directamente en el navegador o Postman.
- Configura CORS si es necesario.
- User
funciona, lo malo es que tiene un problerma que prmero carga los datos y leugo el datatable, parce que para hacer qu primero cargue el datatble solo se puede hacer con ajax, dame un ejemplo de comol istar con ajax mi bd
- Assistant
Para solucionar el problema de que los datos se carguen antes que la tabla DataTable, puedes utilizar la opción de Ajax que proporciona DataTables. De esta manera, puedes esperar a que los datos se carguen completamente antes de inicializar la tabla. Aquí hay un ejemplo de cómo hacerlo:
Paso 1: Modificar el
ProductoServicepara devolver los datos en el formato que DataTables espera.Modifica tu servicio tal que retorne los datos directamente que necesita DataTables:
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { Producto } from '../../models/producto.model'; @Injectable({ providedIn: 'root' }) export class ProductoService { private apiUrl = 'http://localhost:8095/producto'; constructor(private http: HttpClient) {} private handleError(error: HttpErrorResponse) { console.error('Ocurrió un error:', error); return throwError(() => new Error('Error: ')); } listarProductos(): Observable<Producto[]> { return this.http.get<Producto[]>(`${this.apiUrl}/listar`, { withCredentials: true }).pipe( catchError(this.handleError) ); } }Paso 2: Modificar el componente
ProductoListarComponentpara usar Ajax de DataTables.Dentro de tu componente, configura la tabla para usar Ajax:
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subject } from 'rxjs'; import { DataTableDirective } from 'angular-datatables'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-producto-listar', templateUrl: './producto-listar.component.html', styleUrls: ['./producto-listar.component.css'] }) export class ProductoListarComponent implements OnInit, OnDestroy { dtOptions: any = {}; dtTrigger: Subject<any> = new Subject<any>(); constructor(private http: HttpClient) {} ngOnInit(): void { this.dtOptions = { pagingType: 'full_numbers', pageLength: 10, processing: true, serverSide: true, ajax: (dataTablesParameters: any, callback) => { this.http .get<any>('http://localhost:8095/producto/listar') .subscribe((response) => { callback({ recordsTotal: response.length, // Ajusta de acuerdo a tus datos recordsFiltered: response.length, // Ajusta de acuerdo a tus datos data: response }); }); }, columns: [ { title: 'ID', data: 'idproducto' }, { title: 'Fecha', data: 'fecha' }, { title: 'Nombre', data: 'nombre' }, { title: 'Precio Compra', data: 'preciocompra' }, { title: 'Precio Venta', data: 'precioventa' }, { title: 'Imagen', data: 'imagen' }, { title: 'Activo', data: 'activo' }, { title: 'Categoría', data: 'idcategoria' } ] }; } ngOnDestroy(): void { this.dtTrigger.unsubscribe(); } }Paso 3: Actualizar la plantilla del componente (
producto-listar.component.html):<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover"> <thead> <tr> <th>ID</th> <th>Fecha</th> <th>Nombre</th> <th>Precio Compra</th> <th>Precio Venta</th> <th>Imagen</th> <th>Activo</th> <th>Categoría</th> </tr> </thead> <tbody> </tbody> </table>Resumen
En este approach, se usa DataTables con la opción
ajaxpara obtener los datos desde el servidor. Este enfoque asegura que la tabla DataTable se configurará correctamente una vez que los datos hayan sido obtenidos. Si tu backend proporciona la información necesaria (comorecordsTotalyrecordsFiltered) podrías ajustar esos valores en la llamadacallback.Este método simplifica el proceso y aprovecha las capacidades integradas de DataTables para trabajar con datos obtenidos a través de peticiones AJAX.
- User
ajax: (dataTablesParameters: any, callback) => { this.http .get(‘http://localhost:8095/producto/listar’) .subscribe((response) => { callback({ recordsTotal: response.length, // Ajusta de acuerdo a tus datos recordsFiltered: response.length, // Ajusta de acuerdo a tus datos data: response }); }); }, - pero ya tengo el metodo en servidor, hay una forma de hacerlo solo llaand oal metodo pero implementando ajax?
- Assistant
Entiendo que desea usar el método de tu servidor directamente con AJAX proporcionado por DataTables en lugar de realizar una llamada HTTP en el componente manualmente. Esto es posible y aquí te muestro cómo puedes integrarlo.
Paso a paso:
1. Modificar el backend para soportar paginación y filtrado (si no está hecho ya)
Para aprovechar las capacidades de DataTables, es importante que el servidor soporte paginación, filtrado y ordenamiento. Aquí hay un ejemplo básico de cómo se puede realizar en Spring Boot:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class ProductoController { @Autowired private ProductoService productoService; @GetMapping("/producto/listar") public DataTablesResponse<Producto> listarProductos( @RequestParam int start, @RequestParam int length, @RequestParam String search_value, @RequestParam String order_column, @RequestParam String order_dir) { Pageable pageable = PageRequest.of(start / length, length); Page<Producto> productos = productoService.findAll(pageable, search_value, order_column, order_dir); DataTablesResponse<Producto> response = new DataTablesResponse<>(); response.setData(productos.getContent()); response.setRecordsTotal(productoService.count()); response.setRecordsFiltered(productos.getTotalElements()); return response; } }2. Crear la clase
DataTablesResponse:Esta clase ayudará a estructurar la respuesta adecuada para DataTables:
import java.util.List; public class DataTablesResponse<T> { private List<T> data; private long recordsTotal; private long recordsFiltered; public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } public long getRecordsTotal() { return recordsTotal; } public void setRecordsTotal(long recordsTotal) { this.recordsTotal = recordsTotal; } public long getRecordsFiltered() { return recordsFiltered; } public void setRecordsFiltered(long recordsFiltered) { this.recordsFiltered = recordsFiltered; } }3. Modificar tu componente Angular para utilizar AJAX.
En tu componente, configura la tabla directamente para utilizar AJAX como se muestra a continuación:
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-producto-listar', templateUrl: './producto-listar.component.html', styleUrls: ['./producto-listar.component.css'] }) export class ProductoListarComponent implements OnInit { dtOptions: any = {}; constructor(private http: HttpClient) {} ngOnInit(): void { this.dtOptions = { pagingType: 'full_numbers', pageLength: 10, processing: true, serverSide: true, ajax: { url: 'http://localhost:8095/producto/listar', type: 'GET', data: (d: any) => { return { start: d.start, length: d.length, search_value: d.search.value, order_column: d.columns[d.order[0].column].data, order_dir: d.order[0].dir }; } }, columns: [ { title: 'ID', data: 'idproducto' }, { title: 'Fecha', data: 'fecha' }, { title: 'Nombre', data: 'nombre' }, { title: 'Precio Compra', data: 'preciocompra' }, { title: 'Precio Venta', data: 'precioventa' }, { title: 'Imagen', data: 'imagen' }, { title: 'Activo', data: 'activo' }, { title: 'Categoría', data: 'idcategoria' } ] }; } }4. Actualizar la plantilla del componente (
producto-listar.component.html):<table datatable [dtOptions]="dtOptions" class="row-border hover"> <thead> <tr> <th>ID</th> <th>Fecha</th> <th>Nombre</th> <th>Precio Compra</th> <th>Precio Venta</th> <th>Imagen</th> <th>Activo</th> <th>Categoría</th> </tr> </thead> </table>Resumen:
- Backend: Ajusta tu API para soportar paginación, ordenamiento y búsqueda.
- Frontend: Configura DataTables en Angular para usar AJAX con esos parámetros.
- Component Template: Mantén la estructura básica de la tabla y deja que DataTables maneje la renderización basada en AJAX.
Con estas modificaciones, tu DataTable se integrará con tu endpoint en el backend, y solo se cargará una vez que los datos hayan sido recibidos. Esto garantiza que los datos sean vistos correctamente en el momento de la renderización de la tabla.
- User
es demasiado codigo, si ya tengo un archivo servicio que llama a las rutas del controlador spring boot, no necesito crear nada del lado del servido, solo debo hacer algo para usar esearchivo service, encntre un ejmlo de inernet - Hola a todos, finalmente encontré la solución a mi pregunta. Es tan simple como parece.:sonrisa:
Entonces, cuando usas tablas de datos del lado del servidor con Angular, en el archivo del componente .ts, cuando usas Ajax, realizas una llamada directa a alguna URL. Solo usa un servicio que devuelva el observable (en mi caso).
Fragmento de código:
Texto sin formato
this.dtOptions.ajax = (dataTablesParameters: any, callback) => { that.controllerService.getAdminControllers(this.dtOptions.pageLength, dataTablesParameters.start).subscribe(resp => { that.data = resp.data; callback({ recordsTotal: resp.pagination.totalCount, recordsFiltered: resp.pagination.totalCount, data: []
}); console.log(that.data); });}; - paraece que le funciona, esto s pueede aplicar al mio
- Assistant
¡Entiendo tu punto! Puedes utilizar el servicio Angular que ya tienes para realizar la llamada AJAX en tu componente sin necesidad de hacer modificaciones en el lado del servidor. Vamos a implementar un ejemplo basado en el enfoque que encontraste.
Paso 1: Modificar el Servicio
ProductoServiceTu servicio
ProductoServicedebería regresar un observable que se ajuste a tus necesidades. Vamos a asegurarnos de que esté listo para ser utilizado en el componente:import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { catchError, Observable, throwError } from 'rxjs'; import { Producto } from '../../models/producto.model'; @Injectable({ providedIn: 'root' }) export class ProductoService { private apiUrl = 'http://localhost:8095/producto'; constructor(private http: HttpClient) {} private handleError(error: HttpErrorResponse) { console.error('Ocurrió un error:', error); return throwError(() => new Error('Error: ')); } listarProductos(start: number, length: number): Observable<any> { // Ajusta los parámetros según sea necesario return this.http.get<any>(`${this.apiUrl}/listar?start=${start}&length=${length}`, { withCredentials: true }) .pipe(catchError(this.handleError)); } }Paso 2: Modificar el Componente
ProductoListarComponentActualiza tu componente para utilizar AJAX y el servicio que ya tienes:
import { Component, OnInit } from '@angular/core'; import { ProductoService } from '../../services/producto.service'; @Component({ selector: 'app-producto-listar', templateUrl: './producto-listar.component.html', styleUrls: ['./producto-listar.component.css'] }) export class ProductoListarComponent implements OnInit { dtOptions: any = {}; constructor(private productoService: ProductoService) {} ngOnInit(): void { const that = this; // Referencia al contexto de `this` dentro del callback this.dtOptions = { pagingType: 'full_numbers', pageLength: 10, processing: true, serverSide: true, ajax: (dataTablesParameters: any, callback) => { that.productoService .listarProductos(dataTablesParameters.start, dataTablesParameters.length) .subscribe(resp => { callback({ recordsTotal: resp.totalCount, recordsFiltered: resp.totalCount, data: resp.data, }); }); }, columns: [ { title: 'ID', data: 'idproducto' }, { title: 'Fecha', data: 'fecha' }, { title: 'Nombre', data: 'nombre' }, { title: 'Precio Compra', data: 'preciocompra' }, { title: 'Precio Venta', data: 'precioventa' }, { title: 'Imagen', data: 'imagen' }, { title: 'Activo', data: 'activo' }, { title: 'Categoría', data: 'idcategoria' } ] }; } }Paso 3: Actualizar la plantilla del componente (
producto-listar.component.html)Actualiza tu plantilla para que DataTables se encargue de la renderización:
<table datatable [dtOptions]="dtOptions" class="row-border hover"> <thead> <tr> <th>ID</th> <th>Fecha</th> <th>Nombre</th> <th>Precio Compra</th> <th>Precio Venta</th> <th>Imagen</th> <th>Activo</th> <th>Categoría</th> </tr> </thead> </table>Explicación:
- Servicio
ProductoService: Se ajustó para recibir los parámetros necesarios (startylength) y devolver los datos en el formato que DataTables espera. - Componente
ProductoListarComponent:- Configura
dtOptionspara usar AJAX conserverSide: true. - Utiliza el servicio
ProductoServicedentro de la opciónajaxde DataTables. - Los parámetros de
DataTables(startylength) se pasan a la funciónlistarProductos. - La respuesta del servidor se usa para llenar los datos y las métricas necesarias para DataTables (
recordsTotal,recordsFiltered,data).
- Configura
Esta implementación debe funcionar para cargar los datos usando el servicio Angular y asegurar que la tabla solo se inicialice una vez que los datos se hayan recibido.
- Servicio
- User
.listarProductos(dataTablesParameters.start, dataTablesParameters.length) - para que es eso? - responde en una linea
- Assistant
Esos parámetros (
dataTablesParameters.startydataTablesParameters.length) se usan para la paginación, indicando el punto de partida y la cantidad de registros que DataTables necesita del servidor. - User
pero datatable ya hace eso de manera automatica? para que ponerlo? responde en una linea
- Assistant
DataTables lo hace automáticamente en el lado del cliente, pero en el modo servidor (
serverSide: true), debes pasar estos parámetros para que el servidor pagine los datos correctamente. - User
pero con el metodo ngFor eso lo hace en automatico, porque deberia hacerlo asi usando ajax? responde en una linea
- Assistant
Usar AJAX con
serverSide: truemejora el rendimiento en grandes datasets paginando y filtrando en el servidor, en lugar de cargar todos los datos en el cliente. - User
puedo hacerlo sin la paginacion? ya que no creo tener tantos registros
- Assistant
Sí, puedes hacerlo sin paginación, configurando DataTables para que simplemente cargue todos los datos de una vez usando AJAX. Aquí tienes cómo:
Paso 1: Modificar el Servicio
ProductoServiceTu servicio
ProductoServiceno necesita cambios, ya que puede seguir devolviendo todos los productos.Paso 2: Modificar el Componente
ProductoListarComponentConfigura DataTables para cargar todos los datos de una vez, sin paginación en el lado del servidor:
import { Component, OnInit } from '@angular/core'; import { ProductoService } from '../../services/producto.service'; @Component({ selector: 'app-producto-listar', templateUrl: './producto-listar.component.html', styleUrls: ['./producto-listar.component.css'] }) export class ProductoListarComponent implements OnInit { dtOptions: any = {}; constructor(private productoService: ProductoService) {} ngOnInit(): void { const that = this; // Referencia al contexto de `this` dentro del callback this.dtOptions = { pagingType: 'full_numbers', pageLength: 10, processing: true, serverSide: false, // Deshabilita la paginación en el servidor ajax: (dataTablesParameters: any, callback) => { that.productoService.listarProductos(0, 0).subscribe(resp => { callback({ data: resp }); }); }, columns: [ { title: 'ID', data: 'idproducto' }, { title: 'Fecha', data: 'fecha' }, { title: 'Nombre', data: 'nombre' }, { title: 'Precio Compra', data: 'preciocompra' }, { title: 'Precio Venta', data: 'precioventa' }, { title: 'Imagen', data: 'imagen' }, { title: 'Activo', data: 'activo' }, { title: 'Categoría', data: 'idcategoria' } ] }; } }Paso 3: Actualizar la plantilla del componente (
producto-listar.component.html)Asegúrate de que tu plantilla se vea bien:
<table datatable [dtOptions]="dtOptions" class="row-border hover"> <thead> <tr> <th>ID</th> <th>Fecha</th> <th>Nombre</th> <th>Precio Compra</th> <th>Precio Venta</th> <th>Imagen</th> <th>Activo</th> <th>Categoría</th> </tr> </thead> </table>Apuntes Finales:
- Deshabilitar paginación en el servidor: Configura
serverSide: false. - Cargar todos los datos de una vez: Ajusta tu método de servicio para no requerir parámetros de paginación (si no es estrictamente necesario).
Esto hará que DataTables cargue todos los datos desde tu servidor de una sola vez, sin paginación, y muestre todos los registros en la tabla al mismo tiempo.
- Deshabilitar paginación en el servidor: Configura
- User
Se esperaban 0 argumentos, pero se obtuvieron 2 (0, 0) - responde en una linea
- Assistant
Elimina los argumentos
startylengthen la llamada al serviciolistarProductos()para ajustarlo a tu método que no requiere parámetros. - User
Se declara "dataTablesParameters", pero su valor no se lee nunca.ts(6133) (parameter) dataTablesParameters: any - no sale error pero esta sin color porno usarse, es normal, responde en una linea
- Assistant
Sí, es normal ya que
dataTablesParametersno se necesita si no estás usando paginación o filtrado del lado del servidor; puedes eliminar ese parámetro si no lo usas. - User
me sale este error al inicio del lsitado en una arlet - DataTables warning: table id=DataTables_Table_0 - Requested unknown parameter 'idcategoria' for row 0, column 7. For more information about this error, please see https://datatables.net/tn/4 - la web dice esto - Warning: Requested unknown parameter This is possibly the most cryptic warning message that DataTables will show. It is a short error message as it needs to cope with all of the data source options that DataTables has, but flexible enough to convey information for each of these cases, hence why it can appear a little cryptic on first inspection. However, when we break it down into its component parts, it is actually relatively straight forward, as described below.
Note for Charter and Spectrum webmail customers If you have ended up at this page because of an error shown while trying to access your Charter or Spectrum e-mail, please get in touch with their customer support teams and report the error message. Our free open source software is used in the webmail by those companies and a configuration error can result in this message being displayed.
Meaning Each cell in DataTables requests data, and when DataTables tries to obtain data for a cell and is unable to do so, it will trigger a warning, telling you that data is not available where it was expected to be. The warning message is:
DataTables warning: table id={id} - Requested unknown parameter '{parameter}' for row {row-index}, column{column-index}`
where:
{id} is replaced with the DOM id of the table that has triggered the error {parameter} is the name of the data parameter DataTables is requesting {row-index} is the DataTables internal row index (row().index()) for the row that has triggered the error. {column-index} is the column data index (column().index()) for the column that has triggered the error. The column index information was added in DataTables 1.10.10. So to break it down, DataTables has requested data for a given row, of the {parameter} provided and there is no data there, or it is null or undefined (DataTables doesn't know, by default how to display these parameters - see below if your data does contain these values).
Diagnosis The key part to understanding this error message is the {parameter} aspect of it. It will be in one of three forms:
Integer String Function Parameter is an integer When {parameter} is an integer, DataTables is looking for data from an array. This is usually the case when using DOM sourced data (i.e. the data for the table is read automatically from the document). In this circumstance the requested data doesn't exist in source array - likely because the array isn't long enough. This can occur if:
There is a colspan or rowspan in the tbody of the table, which is not supported by DataTables. Using columns or columnDefs you have specified more columns than there are in the HTML The number of cells in the table does not satisfy the equation #cells = #columns * #rows (i.e. there are more columns defined in the header than in the table body, or vice-versa). Parameter is a string If {parameter} is shown as a string, this will typically indicate that you have used columns.data or columns.render to pull data out of an object, be it Ajax loaded or from the client-side. For example the error message in read: Requested unknown parameter 'Name' for row 0. This will indicate that a column which uses columns.data has been unable to obtain valid data to display - for example:
Javascript 1 { data: 'Name' } would produce this error if the data source object for the row had no Name parameter or the data was null or undefined.
As a result, this error usually occurs if:
The data property specified doesn't exist (a typo or a gap in data) The value of the property specified is null Parameter is a function If {parameter} simply says {function} it means that columns.data or columns.render have been given as a function, but the function has returned null or undefined. For example, the following would trigger such an error:
Javascript 1 2 3 4 5 { data: function ( row, type, set ) { if ( type === 'display' ) { return row.Name; } } ); Note how the return statement is only used when type === 'display'. As a result, if type is not display then undefined is the return value from the function and DataTables will throw a warning.
Resolution The key to resolving this error, is to ensure that DataTables has all of the data that is required. Specifically, check the following:
colspan and rowspan have not been used in the tbody of the table. The equation #cells = #columns * #rows is satisfied. If using columns ensure that you have specified exactly the number of columns that are present in the HTML for the table. Also if using
dt-init columns, remove any trailing commas you might have at the end of the array. The additional comma can cause issues for older browsers. If using dt-init columnDefsensure that you have not specified more columns than there are in the HTML If using columns.render or columns.data ensure that they are returning a value (no return in Javascript is the same as returning undefined which will result in this error). Ensure that the server-side script is completing its execution successfully. Long running scripts can time out for example. The server error logs will give an indication if this is the case. null or undefined data null and undefined values in a data source absolutely are valid and very often useful. DataTables warns about the use of them by default, as the majority of the time they are not intended for display - for example, rather than showing null in the table, you might want to show Not yet set, or simply an empty string (empty cell). For this, DataTables has a columns.defaultContent option.With columns.defaultContent set, any null or undefined value will be replaced with the value specified. No warning will be shown in this circumstances.
Comments (3) nprasovic@v1.10.1311:26, Fri 9th Dec 2016 This warning message can also appear if you have columns.render defined as a function but forgot to return something from the function, i.e.:
Javascript 1 2 3 4 5 6 { data: 'id', render: function( data, type, full, meta ) { Utils.formatString(buttonTemplate, data) } } In this case data point id exists in input data, but render function 'returns' undefined (doesn't return anything) and it triggers the warning.
expressiveco@v1.10.1914:48, Mon 2nd Jul 2018 Modifying data returned by data() and removing some property etc. and then calling draw() also causes this error. Thus, it is better to clone row data for modifications.
mmoscz@v1.10.1910:37, Tue 24th Jul 2018 When you define a renderiing function, don't forget to return a value.
The example below will generate this error if data is different from "dummy", because the dataRender variable not has a value assiged...
Javascript 1 2 3 4 5 6 7 function jsRenderCOL(data, type, row, meta) { var dataRender; if (data !== "dummy") { dataRender = "you as dummy"; } return dataRender; } Post new comment Contributions in the form of tips, code snippets and suggestions for the above material are very welcome. To post a comment, please use the form below. Text is formatted by Markdown.
To post comments, please sign in to your DataTables account, or register:
Sign in Register Any questions posted here will be deleted without being published. Please post questions in the Forums. Comments are moderated.
- Assistant
El error ocurre porque DataTables no está encontrando la propiedad
idcategoriaen la respuesta de la API, o bien porque la respuesta no está estructurada como se espera. Necesitamos asegurarnos de que los datos que se devuelven tienen la estructura correcta y que no haya errores tipográficos en las propiedades de los objetos.Paso 1: Verificar la estructura de datos devuelta por la API
Asegúrate de que la API realmente devuelva un array de objetos con las propiedades que esperas (incluyendo
idcategoria).Paso 2: Revisar la configuración de DataTables en tu componente
ProductoListarComponentAsegúrate de que las columnas de DataTables coincidan exactamente con las propiedades del objeto que devuelves desde el backend.
Ejemplo completo
-
Servicio
ProductoService: No necesita cambios si ya está correctamente llamando a la API. -
Componente
ProductoListarComponent:
import { Component, OnInit } from '@angular/core'; import { ProductoService } from '../../services/producto.service'; @Component({ selector: 'app-producto-listar', templateUrl: './producto-listar.component.html', styleUrls: ['./producto-listar.component.css'] }) export class ProductoListarComponent implements OnInit { dtOptions: any = {}; constructor(private productoService: ProductoService) {} ngOnInit(): void { const that = this; // Referencia al contexto de `this` dentro del callback this.dtOptions = { pagingType: 'full_numbers', pageLength: 10, processing: true, serverSide: false, // Deshabilita la paginación en el servidor ajax: (dataTablesParameters: any, callback) => { that.productoService.listarProductos().subscribe(resp => { callback({ data: resp }); }); }, columns: [ { title: 'ID', data: 'idproducto' }, { title: 'Fecha', data: 'fecha' }, { title: 'Nombre', data: 'nombre' }, { title: 'Precio Compra', data: 'preciocompra' }, { title: 'Precio Venta', data: 'precioventa' }, { title: 'Imagen', data: 'imagen' }, { title: 'Activo', data: 'activo' }, { title: 'Categoría', data: 'idcategoria' } ] }; } }Importante
- Asegúrate de que el servicio
listarProductosdevuelva un array de objetos que tengan todas las propiedades esperadas por DataTables. - Comprueba que la propiedad
idcategoriarealmente exista en cada uno de los objetos de la respuesta.
Por ejemplo, tu respuesta de la API debe tener esta estructura:
[ { "idproducto": 1, "fecha": "2022-01-01", "nombre": "Producto 1", "preciocompra": 100.0, "precioventa": 150.0, "imagen": "img1.jpg", "activo": 1, "idcategoria": 1 }, { "idproducto": 2, "fecha": "2022-01-02", "nombre": "Producto 2", "preciocompra": 200.0, "precioventa": 250.0, "imagen": "img2.jpg", "activo": 1, "idcategoria": 2 } ]Esto debería resolver el problema del parámetro desconocido en tus datos, asegurando que DataTables pueda encontrar todas las columnas esperadas en tus datos devueltos por la API.
-
- User
no el jason correcto seria “imagen”: “img2.jpg”, “activo”: 1, "categoria: {sus propio atributos, uno de ellos es el nombre}" - como lo soluciono?
- Assistant
Entiendo, tu estructura JSON tiene una propiedad anidada para
categoria. Esa es una situación común y se puede manejar fácilmente especificando el uso decolumns.dataen DataTables para acceder a las propiedades anidadas.Paso 1: Verificar la estructura del JSON que devuelve la API
Asegúrate de que el JSON devuelto tenga la estructura correcta, algo como esto:
[ { "idproducto": 1, "fecha": "2022-01-01", "nombre": "Producto 1", "preciocompra": 100.0, "precioventa": 150.0, "imagen": "img1.jpg", "activo": 1, "categoria": { "idcategoria": 1, "nombreCategoria": "Categoría 1" } }, { "idproducto": 2, "fecha": "2022-01-02", "nombre": "Producto 2", "preciocompra": 200.0, "precioventa": 250.0, "imagen": "img2.jpg", "activo": 1, "categoria": { "idcategoria": 2, "nombreCategoria": "Categoría 2" } } ]Paso 2: Modificar el Componente
ProductoListarComponentConfigurar DataTables para acceder a la propiedad anidada
categoria.nombreCategoria:import { Component, OnInit } from '@angular/core'; import { ProductoService } from '../../services/producto.service'; @Component({ selector: 'app-producto-listar', templateUrl: './producto-listar.component.html', styleUrls: ['./producto-listar.component.css'] }) export class ProductoListarComponent implements OnInit { dtOptions: any = {}; constructor(private productoService: ProductoService) {} ngOnInit(): void { const that = this; // Referencia al contexto de `this` dentro del callback this.dtOptions = { pagingType: 'full_numbers', pageLength: 10, processing: true, serverSide: false, // Deshabilita la paginación en el servidor ajax: (dataTablesParameters: any, callback) => { that.productoService.listarProductos().subscribe(resp => { callback({ data: resp }); }); }, columns: [ { title: 'ID', data: 'idproducto' }, { title: 'Fecha', data: 'fecha' }, { title: 'Nombre', data: 'nombre' }, { title: 'Precio Compra', data: 'preciocompra' }, { title: 'Precio Venta', data: 'precioventa' }, { title: 'Imagen', data: 'imagen' }, { title: 'Activo', data: 'activo' }, { title: 'Categoría', data: 'categoria.nombreCategoria' } ] }; } }Explicación:
- Configuración de columnas con propiedades anidadas: Utiliza
data: 'categoria.nombreCategoria'para acceder a la propiedad anidadanombreCategoriadentro del objetocategoria.
Plantilla del componente (
producto-listar.component.html)Asegúrate de que tu plantilla sea similar a la siguiente:
<table datatable [dtOptions]="dtOptions" class="row-border hover"> <thead> <tr> <th>ID</th> <th>Fecha</th> <th>Nombre</th> <th>Precio Compra</th> <th>Precio Venta</th> <th>Imagen</th> <th>Activo</th> <th>Categoría</th> </tr> </thead> </table>Resumen:
- Estructura de la respuesta del servidor: Asegúrate de que el JSON tenga las propiedades anidadas correctamente.
- Acceso a propiedades anidadas con DataTables: Configura las columnas en DataTables para acceder a las propiedades anidadas utilizando notación de puntos (
data: 'categoria.nombreCategoria').
Esto debería resolver el problema de la "propiedad desconocida" al asegurar que DataTables puede acceder a todas las propiedades, incluidas las anidadas.
- Configuración de columnas con propiedades anidadas: Utiliza
- User
responde en una linea, ajax me segura actualizacion en tiempo real no es cierto?
- Assistant
No, AJAX no asegura actualizaciones en tiempo real; para eso necesitarías WebSockets o técnicas de polling a intervalos regulares.
- User
pero de manera local? respodne en una linea
- Assistant
De manera local, AJAX puede actualizar datos al recargar la página o hacer peticiones periódicas, pero no en tiempo real sin técnicas adicionales.
- User
pero he visto ejmplos en intenet como hacer registros o eliminaciones y si se actualzia la lista sin actualziar la pagina, como se hace eso?
- Assistant
Para actualizar la lista tras registros o eliminaciones sin recargar la página, puedes realizar una petición AJAX después de cada operación y actualizar el DataTable con los nuevos datos de esta forma:
// Después de una operación de registro o eliminación this.productoService.listarProductos().subscribe(resp => { this.dataTableInstance.clear().rows.add(resp).draw(); });En el contexto de Angular, puedes utilizar el método de servicio para hacer la petición y luego refrescar la DataTable con los datos obtenidos.
- User
ajax: (dataTablesParameters: any, callback) => { that.productoService.listarProductos().subscribe(resp => { callback({ data: resp }); }); },
- lo coloco hay? responde en 2 lineas donde y para que sirve en 1 lina
- Assistant
Colócalo en la configuración
ajaxde DataTables enngOnInitpara cargar y actualizar datos dinámicamente sin recargar la página. - User
exactamente dodne
- Assistant
Colócalo dentro de
ngOnInit, en la configuración dedtOptions, reemplazando la parteajaxpara que se carguen los datos usando tu servicio:ngOnInit(): void { const that = this; // Referencia al contexto de `this` dentro del callback this.dtOptions = { pagingType: 'full_numbers', pageLength: 10, processing: true, serverSide: false, ajax: (dataTablesParameters: any, callback) => { that.productoService.listarProductos().subscribe(resp => { callback({ data: resp }); }); }, columns: [ { title: 'ID', data: 'idproducto' }, { title: 'Fecha', data: 'fecha' }, { title: 'Nombre', data: 'nombre' }, { title: 'Precio Compra', data: 'preciocompra' }, { title: 'Precio Venta', data: 'precioventa' }, { title: 'Imagen', data: 'imagen' }, { title: 'Activo', data: 'activo' }, { title: 'Categoría', data: 'categoria.nombreCategoria' } // Para propiedades anidadas ] }; } - User
me refiero a la actualziacion en tiempo real - this.dataTableInstance.clear().rows.add(resp).draw(); - esto dond lo coloco
- Assistant
Para actualizar el DataTable en tiempo real después de una operación como registro o eliminación, coloca
this.dataTableInstance.clear().rows.add(resp).draw();dentro de la lógica donde manejas la respuesta de tu operación de registro o eliminación.Ejemplo Completo:
- Inicializa la instancia de DataTable en
ngOnInit:
import { Component, OnInit, ViewChild } from '@angular/core'; import { DataTableDirective } from 'angular-datatables'; import { ProductoService } from '../../services/producto.service'; @Component({ selector: 'app-producto-listar', templateUrl: './producto-listar.component.html', styleUrls: ['./producto-listar.component.css'] }) export class ProductoListarComponent implements OnInit { @ViewChild(DataTableDirective, { static: false }) datatableElement: DataTableDirective; // Referencia a la instancia de DataTable dtOptions: any = {}; constructor(private productoService: ProductoService) {} ngOnInit(): void { const that = this; this.dtOptions = { pagingType: 'full_numbers', pageLength: 10, processing: true, serverSide: false, ajax: (dataTablesParameters: any, callback) => { that.productoService.listarProductos().subscribe(resp => { callback({ data: resp }); }); }, columns: [ { title: 'ID', data: 'idproducto' }, { title: 'Fecha', data: 'fecha' }, { title: 'Nombre', data: 'nombre' }, { title: 'Precio Compra', data: 'preciocompra' }, { title: 'Precio Venta', data: 'precioventa' }, { title: 'Imagen', data: 'imagen' }, { title: 'Activo', data: 'activo' }, { title: 'Categoría', data: 'categoria.nombreCategoria' } ] }; } refreshTable(): void { this.productoService.listarProductos().subscribe(resp => { this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => { dtInstance.clear().rows.add(resp).draw(); }); }); } }- Llama a
refreshTabledespués de una operación de registro o eliminación:
Por ejemplo, después de agregar un producto:
addProduct(nuevoProducto: Producto): void { this.productoService.addProducto(nuevoProducto).subscribe(() => { this.refreshTable(); // Refresca la tabla después de agregar el producto }); }Recapitulación
refreshTable(): Método que recarga los datos de la tabla.- Llama a
refreshTable()después de una operación que modifique los datos (registro/eliminación) para actualizar el DataTable en tiempo real.
- Inicializa la instancia de DataTable en
- User
por ejemplo encontre este video - [Música] hola a todos cómo están bueno en este
vídeo les voy a compartir un proyecto que es un crudo utilizando data tables y
algunas funciones que no vimos en el curso de crudo desde cero que tienen que
ver con allá por ejemplo hasta que es muy simple y se llama el
ajax punto reloj acá tienen todas las opciones dentro de
documentación oficial hemos trabajado con estas propiedades
javascript para estas funciones perdón bueno hay muchísimas cosas para ver y
también en este proyecto para los iconos
que son para crear editar y eliminar
he utilizado estas fuentes de material design
de de google como hacemos nos referenciamos con esta
simple línea
acá las fuentes de google con material y cons y luego si queremos por ejemplo
aplicar en el caso del botón dar de alta por ejemplo pueden usar el
que quiera acá tienen toda la variedad simplemente buscan el icono que quieren
y la referencia en de una manera muy simple que es conecta con este tag que
está encerrado la etiqueta y utiliza la clase material y cons y el nombre del
componente miren de simple que es por ejemplo
busquemos saber algunos de toda la variedad que tienen
lo mismo por ejemplo acá
seleccionamos iconos seleccionado y acá nos dice para miren lo que necesitamos
copiamos esta parte y lo vamos a poner para que se vea en
este icono
entonces quitamos este tags una letra y ponemos el que hemos seleccionado
vamos a acomodar esto guardamos recargamos y ya tienen este
simbolito pueden buscar eligen el que ustedes necesiten el que quieran
y tienen una gran variedad vienen acá lo mismo aplique para esta hora les muestro
cómo se aplica por cada fila vamos a dejar el anterior
estaba bien y lo tenemos aquí
el proyecto es como tan simple como lo que venimos realizando tenemos una
plantilla de postre estamos aplicando estilos de bus trap
tenemos una tabla y marcamos le damos una idea a esta tabla tabla usuarios en
este caso definimos el tejado y en el body o lo definimos pero no ponemos nada
adentro luego he creado una ventana modal que con la misma ventana modal de
postre vamos a utilizar el formulario de alta y de edición
esto funciona perfecto para eso les diría que para hasta 5.000 registros en
este caso estamos probando con mil registros ahora les muestro lo sencillo
que es bueno esto lo de los iconos
y luego hacemos referencia como siempre a los archivos que utilizamos de bus
trap y de data tables para el crudo utilizamos esto casi no
varió creo que algún sweet saca que antes lo ponía en el crudo que les dejo
en la descripción o en las tarjetas que aparece en el vídeo les dejo para que lo
vean porque está explicado desde cero desde la interacción de guam server en
este caso les estoy mostrando y les dejo el proyecto para que lo descarguen lo
modifiquen y prueben y lo adapten a sus necesidades
en ese momento utilice una consulta acá en este archivo index.php que estaba esa
consulta la puse aquí en cruz entonces tenemos recibimos los datos enviados por
ajax de los formularios que vamos a modificar
que cada formulario va a tener él el nombre de usuario recuerden que el
cluster haití en este caso es auto incremental
y lo que estamos añadiendo y modificando son estos campos username primer nombre
último nombre género password y estaba de bases de datos como ya vimos en los
cursos anteriores son bases de prueba muy útiles porque ya tenemos armado todo
en esto en cuanto al crudo el index
es muy similar a la anterior lo único que puedo haber cambiado
es la forma en la distribución acá en este formulario nada más
y como les decía
aquí estamos en la base de datos usuarios
vamos a ver la tabla usuarios
y tiene activado el auto incremento
es decir el primer campo de la tabla es clave principal y tiene auto incremental
vamos a poner acá con sql
en los registros en este caso son 1000 si nos vamos al último acá tenemos el
registro número un número 1000 y para dar de alta y que lo vaya poniendo 1001
mil 2003 hay que asegurarse de que hayamos reiniciado ese contador
como lo verificamos
con esta sentencia en sql
y ahora nos vamos al registro número 1000 y cuando demos de alta un nuevo
usuario lo va a hacer con el número 1001 hagamos la prueba vamos a poner
un usuario
j
pero no me va a ser jorge apellido pérez último nombre pérez
género masculino password cualquier número estado
cualquiera le damos guardar y lo que va a hacer es ya estamos en el archivo
el main punto 6 con javascript y con sí query
va a tomar los datos
y acá tengo miren acá todas las funciones
acá tenemos el que es para dar de alta vete en el nuevo presionando el bet en
el nuevo qué es este botón
y le mandamos la opción 1 a donde a éste formulario
que todo esto está dentro de un fórmula que está en una ventana modal y dentro
de la ventana modal está este formulario como le expliqué al detalle en ese curso
que espero que lo vean acá evitamos el comportamiento normal del psuv mil es
decir recarga la página con con una prevén default pasamos todos los datos
que hemos cargado jpr jorgito estos datos enviamos a ajax
al cruz y como tiene la opción 1 va a ir a por la opción de alta aquí va a venir
por iba a ser un insert y luego nos devuelve
este es el registro para que lo dibujemos con
esta función anteriormente había hecho un jason parce bueno eso ya no lo
utilizo y lo único que ponemos es tabla usuarios
qué es lo que estamos referenciando acá cuando creamos nuestra tabla cuando
inicializa moscón data tables selassie se le asignamos en esa variable y
aplicamos haya que lautner false para que no recarguen no se vea el momento en
que recarga a ver veamos le damos guardar
y lo debería crear acá 1001
acá está lo creo solo que ya estaba en 10 y lo creo
si modificamos modifiquemos acá de cualquier página de estas páginas el 17
miller 64 presionamos clic y nos toma todos los datos de esta fila 1064 como
hizo eso cuando presionamos el botón editar
recuerden que aplicamos un documento un clic btn editar en la clase de los
botones tiene que ser con clase porque porque el botón editar se va a repetir
tantas veces como tantas filas hayas al igual que el botón eliminar el botón
crear no porque está fijo en en el formulario principal en la página
principal el index php cualquier duda me la deja en los
comentarios creo que el código está muy detallado pero igual si tienen dudas o
algo que se me esté pasando hombre pregunta entonces capturamos los valores
se lo pasamos a los campos en este momento ya tenemos los valores
en los campos acá lo único que hago de modificar el head era el título el color
para mostrar el modal que es todo esto recuerden es tradición no sólo modal
bueno miller 64 vamos a poner acá primer nombre le vamos a poner miller
vamos a poner miller
a ver que he perdido puede ser
cualquiera stefan a ver y estamos acá miren
lo que va a pasar esto llega también vamos a cambiar el loser name va a ser m
vamos a poner que tenga el primero en la primera letra y el restaurante
acá presten atención acá le vamos a dar guardar y va a hacer el ajax reload con
estos dos parámetros que están acá en la página oficial con un default que lo que
hace es no mostrar toda la recarga a la página de la tabla perdón de la tabla no
de la página porque obviamente estamos trabajando con ella entonces estamos acá
y lo va a modificar a guardar y lo modificó
está este código es funciona muy bien como les decía hasta cinco mil registros
prevén 10.000 digamos para bases chicas el resto lo vimos ayer con server site
ya para la base para grandes bases y miren lo simple que es lo que tiene el
success del ajax tiene una sola línea y luego
que hace la operación oculta el modal bueno para la función de eliminar no
modifique nada simplemente era la que ya tenía por ejemplo vamos a
sacar el registro 19 le vamos a dar a aceptar estamos
capturando ya el dato acá nos dice capturamos el 19 que es lo que estamos
capturando a capturamos la fila en esa tabla y dentro de la fila tomamos el juz
el aire es decir la posición 0 recuerden que acá se cuenta 0 1 2 por
columnas 0 1 2 3 4 5 6 y la última 7 que tiene dos botones editar eliminar
enviamos al crudo con la opción 3 es decir elimina
por la sentencia sql
borra ese registro y lo que estamos haciendo después es
nuevamente contado a los usuarios que ahora tenemos a esa variable
con esta propiedad row y aplicamos esto que se remueve draw miren
va a remover la 19 tras aceptar
18 ediciones out se eliminó que 220
bueno por ejemplo vamos a buscar desde aquí el usuario que habíamos cargado
de la jota pérez nos ponemos acá en la primera
y ponemos j.pérez y está funcionando todo entonces tenemos todas las
operaciones de lo que se llama mantenimiento cruz sobre una base de
datos y está funcionando perfecto
entonces qué otra cosita más acá esta parte
cuando recién tomamos la
mostramos esta tabla le voy a dar a recargar como si fuese la primera vez
que ingresamos al proyecto recarga lo que hace le enviamos la opción 4 cuando
carga la página enviamos la opción 4 y en la opción 4 lo que hace es un
select nos muestra nos trae todos los registros de la tabla usuarios
y esto ya lo vimos utilizamos esta propiedad
ajax acá le pasamos la opción en este caso ya la cargamos con la opción 4
el data sur se va vacío y las columnas también en este son mucho más simples de
graficar utilizamos esta propiedad data y ponemos exactamente el nombre de cada
campo o columna d de la tabla real que tenemos en el
gestor php de miami y para hacer lugar al botón utilizamos
esta que se de fall content y entre comillas dobles recuerden acá si
ponemos comillas doble aquí todo lo que sea con comillas tiene que ir simple
para que no les ponemos un código html que tiene las propiedades de postre ya
que estamos trabajando con bus trap y de esa manera generamos por cada fila
estos dos botones que ya vieron la funcionalidad
y están funcionando perfectamente bueno espero que les haya gustado
insisto les recomiendo que vean el otro curso que tiene la filosofía de la
creación desde cero a que esté explicado de una manera más rápida
y bueno les dejo el código así este los modifican y si la hacen arreglos
también me pueden avisar los subimos los compartimos con la comunidad
con todos este los suscriptores muchas gracias y les
gustó me dejan un like nos vemos el próximo vídeo chao - donde lo hace pero con php, yo estoy en angular, nalaiza todo y dime cuales la forma mas actual de hacer eso?
- Assistant
Para realizar operaciones CRUD (Crear, Leer, Actualizar, Eliminar) en Angular sin recargar la página y actualizar automáticamente la tabla de datos, puedes utilizar AJAX para comunicarte con el backend y actualizar la tabla usando DataTables. A continuación, te muestro cómo hacerlo al estilo más moderno en Angular:
Resumen del Proceso:
- Configurar DataTables en Angular con AJAX.
- Llamar al backend utilizando servicios Angular.
- Actualizar DataTables después de cada operación CRUD sin recargar la página.
Paso a paso:
1. Configurar DataTables en Angular:
Primero, asegúrate de que tienes los siguientes paquetes instalados en tu proyecto Angular:
npm install angular-datatables npm install jquery datatables.net --save2. Modificar el Servicio
ProductoService:Ya tienes un servicio que realiza las llamadas al backend, solo asegúrate de que tiene los métodos necesarios para CRUD.
3. Componente
ProductoListarComponent:Modifica tu componente para inicializar DataTables y actualizar los datos utilizando AJAX después de las operaciones CRUD.
import { Component, OnInit, ViewChild } from '@angular/core'; import { DataTableDirective } from 'angular-datatables'; import { Subject } from 'rxjs'; import { ProductoService } from '../../services/producto.service'; import { Producto } from '../../models/producto.model'; @Component({ selector: 'app-producto-listar', templateUrl: './producto-listar.component.html', styleUrls: ['./producto-listar.component.css'] }) export class ProductoListarComponent implements OnInit { @ViewChild(DataTableDirective, { static: false }) datatableElement: DataTableDirective; dtOptions: any = {}; dtTrigger: Subject<any> = new Subject(); constructor(private productoService: ProductoService) {} ngOnInit(): void { this.dtOptions = { pagingType: 'full_numbers', pageLength: 10, processing: true, serverSide: false, ajax: (dataTablesParameters: any, callback) => { this.productoService.listarProductos().subscribe(resp => { callback({ data: resp }); }); }, columns: [ { title: 'ID', data: 'idproducto' }, { title: 'Fecha', data: 'fecha' }, { title: 'Nombre', data: 'nombre' }, { title: 'Precio Compra', data: 'preciocompra' }, { title: 'Precio Venta', data: 'precioventa' }, { title: 'Imagen', data: 'imagen' }, { title: 'Activo', data: 'activo' }, { title: 'Categoría', data: 'categoria.nombreCategoria' } ] }; this.dtTrigger.next(); } refreshTable(): void { this.productoService.listarProductos().subscribe(resp => { this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => { dtInstance.clear().rows.add(resp).draw(); }); }); } addProduct(nuevoProducto: Producto): void { this.productoService.addProducto(nuevoProducto).subscribe(() => { this.refreshTable(); }); } updateProduct(producto: Producto): void { this.productoService.updateProducto(producto).subscribe(() => { this.refreshTable(); }); } deleteProduct(id: number): void { this.productoService.deleteProducto(id).subscribe(() => { this.refreshTable(); }); } }4. Plantilla del Componente (
producto-listar.component.html):<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover"> <thead> <tr> <th>ID</th> <th>Fecha</th> <th>Nombre</th> <th>Precio Compra</th> <th>Precio Venta</th> <th>Imagen</th> <th>Activo</th> <th>Categoría</th> <th>Acciones</th> </tr> </thead> <tbody> <tr *ngFor="let producto of productos"> <td>{{ producto.idproducto }}</td> <td>{{ producto.fecha }}</td> <td>{{ producto.nombre }}</td> <td>{{ producto.preciocompra }}</td> <td>{{ producto.precioventa }}</td> <td>{{ producto.imagen }}</td> <td>{{ producto.activo }}</td> <td>{{ producto.categoria.nombreCategoria }}</td> <td> <!-- Botones de acción --> <button (click)="updateProduct(producto)">Editar</button> <button (click)="deleteProduct(producto.idproducto)">Eliminar</button> </td> </tr> </tbody> </table>Resumen:
- Inicia DataTables: Configura opciones de DataTables dentro de
ngOnInit. - Actualizar la tabla: Usa
refreshTablepara refrescar los datos después de cada operación CRUD. - Operaciones CRUD: Llama a la función
refreshTabledespués de añadir, actualizar o eliminar un producto para actualizar la tabla sin recargar la página.
- User
sin usar esto porque no carga bien el datatable, ya tengo el ajax - <tr *ngFor=“let producto of productos”> {{ producto.idproducto }} {{ producto.fecha }} {{ producto.nombre }} {{ producto.preciocompra }} {{ producto.precioventa }} {{ producto.imagen }} {{ producto.activo }} {{ producto.categoria.nombreCategoria }} - hay una forma de colocar botones que se repitan portodas lastablas de bd, antes usaba estos botones - <button class="btn btn-warning btnActualizar me-1" [routerLink]="['/usuario/actualizar', usuario.idusuario]"> <button class="btn btn-danger btnEliminar" (click)="mensajeConfirmacion(usuario.idusuario, usuario.email)"> - como los puedo impleemntar en ajax? en el video se ve comolo hace y te di el contenido, este es mi metodo apraeliminar - mensajeConfirmacion(id: number, producto: string): void { Swal.fire({ title: "¿Estás seguro?", icon: "warning", showCancelButton: true, confirmButtonColor: "#28a745", cancelButtonColor: "#d33", confirmButtonText: "Si, ¡elimínalo!", cancelButtonText: "Cancelar" }).then((result) => { if (result.isConfirmed) { this.eliminar(id, producto); } }); }
mostrarNotificacion(titulo: string, texto: string, icono: 'success' | 'error'): void { Swal.fire({ title: titulo, text: texto, icon: icono }); }
eliminar(id:number, producto: string): void { this.productoService.eliminarProducto(id).subscribe({ next: () => { this.mostrarNotificacion("Eliminado", "El producto " + producto + "ha sido eliminado", "success") }, error: (error) => { console.error('Error al eliminar producto', error); this.mostrarNotificacion("Error", "Hubo un problema al eliminar el producto: " + producto, "error"); } }) }
- como lo hago con ajax? ya que ngfor hace que primero se cargue el lsitado y luego el datatable
- Assistant
Para implementar botones de acción como "Actualizar" y "Eliminar" en cada fila de DataTables usando AJAX, podemos utilizar la configuración de DataTables sin necesidad de
ngForen el HTML. En lugar de eso, definimos las columnas y las acciones dentro de la configuración de DataTables.Paso a paso:
1. Actualizar el Componente
ProductoListarComponentVamos a agregar los botones de acción dentro de la configuración de las columnas de DataTables y manejaremos los eventos
clicken Angular:import { Component, OnInit, ViewChild } from '@angular/core'; import { DataTableDirective } from 'angular-datatables'; import { Subject } from 'rxjs'; import { ProductoService } from '../../services/producto.service'; import { Producto } from '../../models/producto.model'; import Swal from 'sweetalert2'; @Component({ selector: 'app-producto-listar', templateUrl: './producto-listar.component.html', styleUrls: ['./producto-listar.component.css'] }) export class ProductoListarComponent implements OnInit { @ViewChild(DataTableDirective, { static: false }) datatableElement: DataTableDirective; dtOptions: any = {}; dtTrigger: Subject<any> = new Subject(); constructor(private productoService: ProductoService) {} ngOnInit(): void { const that = this; this.dtOptions = { pagingType: 'full_numbers', pageLength: 10, processing: true, serverSide: false, ajax: (dataTablesParameters: any, callback) => { that.productoService.listarProductos().subscribe(resp => { callback({ data: resp }); }); }, columns: [ { title: 'ID', data: 'idproducto' }, { title: 'Fecha', data: 'fecha' }, { title: 'Nombre', data: 'nombre' }, { title: 'Precio Compra', data: 'preciocompra' }, { title: 'Precio Venta', data: 'precioventa' }, { title: 'Imagen', data: 'imagen' }, { title: 'Activo', data: 'activo' }, { title: 'Categoría', data: 'categoria.nombreCategoria' }, { title: 'Acciones', data: null, render: function(data, type, row) { return ` <button class="btn btn-warning btnActualizar me-1" data-id="${row.idproducto}">Actualizar</button> <button class="btn btn-danger btnEliminar" data-id="${row.idproducto}" data-nombre="${row.nombre}">Eliminar</button> `; } } ] }; } ngAfterViewInit(): void { const that = this; this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => { dtInstance.on('click', '.btnActualizar', function(event) { const id = $(this).data('id'); // Aquí puedes redirigir a la página de actualización o abrir un modal de actualización }); dtInstance.on('click', '.btnEliminar', function(event) { const id = $(this).data('id'); const nombre = $(this).data('nombre'); that.mensajeConfirmacion(id, nombre); }); }); } refreshTable(): void { this.productoService.listarProductos().subscribe(resp => { this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => { dtInstance.clear().rows.add(resp).draw(); }); }); } mensajeConfirmacion(id: number, producto: string): void { Swal.fire({ title: '¿Estás seguro?', icon: 'warning', showCancelButton: true, confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Si, ¡elimínalo!', cancelButtonText: 'Cancelar' }).then((result) => { if (result.isConfirmed) { this.eliminar(id, producto); } }); } mostrarNotificacion(titulo: string, texto: string, icono: 'success' | 'error'): void { Swal.fire({ title: titulo, text: texto, icon: icono }); } eliminar(id: number, producto: string): void { this.productoService.eliminarProducto(id).subscribe({ next: () => { this.mostrarNotificacion('Eliminado', 'El producto ' + producto + ' ha sido eliminado', 'success'); this.refreshTable(); }, error: (error) => { console.error('Error al eliminar producto', error); this.mostrarNotificacion('Error', 'Hubo un problema al eliminar el producto: ' + producto, 'error'); } }); } }2. Actualizar la plantilla HTML:
Solo necesitas la tabla sin
ngForporque los datos se manejarán mediante AJAX:<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover"> <thead> <tr> <th>ID</th> <th>Fecha</th> <th>Nombre</th> <th>Precio Compra</th> <th>Precio Venta</th> <th>Imagen</th> <th>Activo</th> <th>Categoría</th> <th>Acciones</th> </tr> </thead> </table>Explicación:
- Botones de acción en cada fila: Los botones "Actualizar" y "Eliminar" se generan para cada fila usando la opción
renderen la configuración decolumns. - Manejadores de evento: Usamos
dtInstance.on('click', ...)para capturar los eventosclicken los botones "Actualizar" y "Eliminar", y entonces llamar a las funciones correspondientes en Angular. - Eliminación de productos: La eliminación se maneja mostrando primero una confirmación con SweetAlert, y luego llamando al servicio para eliminar el producto y refrescar la tabla.
En resumen, con esta configuración, puedes manejar operaciones CRUD y actualizar la tabla en tiempo real utilizando AJAX y DataTables en Angular sin necesidad de una recarga completa de la página.
- Botones de acción en cada fila: Los botones "Actualizar" y "Eliminar" se generan para cada fila usando la opción