es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Cómo agregar proveedores, servicios e interceptores solo para el módulo de tarjetas de regalo en Angular?

Estoy implementando el almacenamiento en caché solo para el módulo de tarjetas de regalo y he creado el http-cache.service e interceptor de caché. Cuando agrego el servicio en app.module.ts funciona, pero necesito implementarlo por separado solo para las tarjetas de regalo. Cuando lo hago por separado para las tarjetas de regalo, no funciona. Este es mi código.

giftcard-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { GiftcardComponent } from './list/giftcard.component';
import { GiftcardtransactionComponent } from './giftcardtransaction/giftcardtransaction.component';

const routes: Routes = [
    {
      path: '',
      component: GiftcardComponent
    },
    {
      path: 'sales',
      component: GiftcardtransactionComponent,
      data: { breadcrumb: "Sales" }
    }   
  ];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]

})
export class GiftCardRoutingModule { }

giftcard.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { GiftcardComponent } from './list/giftcard.component';
import { GiftcardtransactionComponent } from './giftcardtransaction/giftcardtransaction.component';
import { GiftCardRoutingModule } from './giftcard-routing.module';
import { CacheInterceptor } from '../helper/interceptors/cache.interceptor';
import { HttpCacheService } from '../helper/services/cache/http-cache.service';
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";

@NgModule({
    imports: [
        CommonModule,
        GiftCardRoutingModule,
        RouterModule        
    ],
    declarations: [
        GiftcardComponent,
        GiftcardtransactionComponent        
  ],
  providers: [
    HttpCacheService,{ provide: HTTP_INTERCEPTORS, useClass: CacheInterceptor, multi: true }
  ],
})
export class GiftCardModule { }
Tags:  , , , ,

Answer

  1. Avatar for davy.ai

    Para implementar la memoria caché solo para el módulo de tarjetas de regalo, debes seguir estos pasos:

    1. Crea un módulo separado para la memoria caché en el módulo de tarjetas de regalo.
    2. Importa el módulo de la memoria caché en el módulo de tarjetas de regalo.

    3. Elimina el proveedor para HttpCacheService y CacheInterceptor del archivo app.module.ts.

    4. Agrega el proveedor de HttpCacheService y CacheInterceptor al módulo de tarjetas de regalo.

    5. Cambia el CacheInterceptor para que solo almacene en caché las solicitudes para el módulo de tarjetas de regalo.

    Aquí tienes el código modificado para implementar la memoria caché solo para el módulo de tarjetas de regalo:

    giftcard-cache.module.ts

    import { NgModule } from '@angular/core';
    import { HttpCacheService } from '../helper/services/cache/http-cache.service';
    import { CacheInterceptor } from '../helper/interceptors/cache.interceptor';
    
    @NgModule({
      providers: [
        HttpCacheService,
        { provide: HTTP_INTERCEPTORS, useClass: CacheInterceptor, multi: true }
      ]
    })
    export class GiftCardCacheModule {}
    

    giftcard.module.ts

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { RouterModule } from '@angular/router';
    import { GiftcardComponent } from './list/giftcard.component';
    import { GiftcardtransactionComponent } from './giftcardtransaction/giftcardtransaction.component';
    import { GiftCardRoutingModule } from './giftcard-routing.module';
    import { HttpCacheService } from '../helper/services/cache/http-cache.service';
    import { CacheInterceptor } from '../helper/interceptors/cache.interceptor';
    import { GiftCardCacheModule } from './giftcard-cache.module';
    
    @NgModule({
        imports: [
            CommonModule,
            GiftCardRoutingModule,
            RouterModule,
            GiftCardCacheModule
        ],
        declarations: [
            GiftcardComponent,
            GiftcardtransactionComponent
        ]
    })
    export class GiftCardModule {}
    

    cache.interceptor.ts

    import { Injectable } from '@angular/core';
    import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
    import { Observable, of } from 'rxjs';
    import { HttpCacheService } from '../services/cache/http-cache.service';
    import { tap } from 'rxjs/operators';
    
    @Injectable()
    export class CacheInterceptor implements HttpInterceptor {
    
      constructor(private httpCacheService: HttpCacheService) { }
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<><any>> {
    
        // Verifica si la solicitud es para el módulo de tarjetas de regalo
        if (req.url.includes('/giftcard/')) {
    
          const cachedResponse: HttpResponse<any> = this.httpCacheService.get(req.url);
          if (cachedResponse) {
            console.log('Devuelve respuesta en caché para ', req.url);
            return of(cachedResponse);
          }
    
          return next.handle(req).pipe(
            tap(event => {
              if (event instanceof HttpResponse) {
                console.log('Agregando elemento a la caché: ', req.url);
                this.httpCacheService.put(req.url, event);
              }
            })
          );
        }
        else {
          return next.handle(req);
        }
      }
    }</any></any></any>
    

Comments are closed.