如何添加供应商,服务和拦截器只为礼品卡模块的角度



我只为礼品卡模块实现缓存,并创建了http-cache.service和缓存拦截器。当我在app.module.ts中添加服务时,它可以工作,但我需要单独实现这一点,仅用于礼品卡。当我单独处理礼品卡时,它不起作用。这是我的代码

礼品卡例程模块.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 { }

礼品卡模块.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 { }

当您引用模块中的服务时,会发生哪个错误?

你的模块只导入一次吗?

我还发现您的路由声明有问题。您已导入giftcard routing.module.ts中的路由器模块并将其导出到其他位置。

您不需要在礼品卡.Module.ts中单独导入路由器模块这也可能导致出现一些问题

您可以在应用程序的任何位置注入UserService。

服务本身是CLI生成的类,并用@Injectable((进行修饰。默认情况下,这个装饰器有一个providedIn属性,它为服务创建一个提供程序。在这种情况下,providedIn:'root'指定Angular应该在根注入器中提供服务。

import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class UserService {
}

还可以指定应在特定的@NgModule中提供服务。例如,如果您不希望UserService可用于应用程序,除非它们导入您创建的UserModule,则可以指定应在模块中提供该服务:

import { Injectable } from '@angular/core';
import { UserModule } from './user.module';
@Injectable({
providedIn: UserModule,
})
export class UserService {
}

最新更新