Angular项目CacheService注册报错与服务空引用异常如何解决
问题根源
- Angular的@NgModule各配置项有明确分工,你把服务类放在了错误的配置位置:
declarations:仅可声明组件、指令、管道三类带有对应装饰器的类,服务不属于该范围imports:仅可导入其他Angular模块(带@NgModule装饰器的类),服务不属于该范围
LibraryService未添加@Injectable装饰器,Angular依赖注入体系无法识别它,无法自动注入构造函数中的HttpClientService参数,导致this._http为undefined
修复步骤
- 给LibraryService添加@Injectable装饰器
修改你的library.ts文件,给服务类加上@Injectable注解:
import { Injectable, Inject } from '@angular/core'; import { HttpClientService } from '../cache/http-client.service'; import { Observable } from 'rxjs' // 模型相关导入 import { Path } from './path'; import { Topic } from './topic'; import { Sector } from './sector'; @Injectable() // 新增这一行 export class LibraryService { public sectors: Sector[]; private api; constructor(private _http: HttpClientService, @Inject('BASE_URL') baseUrl: string) { this.api = baseUrl + 'sector'; } getAll(): Observable<Sector[]> { return this._http.get<Sector[]>({ url: this.api, cacheMins: 5 }) } }
- 修正AppModule的配置
删掉declarations数组中的CacheService、HttpClientService、LibraryService,将这三个服务和你用到的BASE_URL注入令牌放到providers数组中:
@NgModule({ declarations: [ AppComponent, NavMenuComponent, HomeComponent, FetchLibrariesComponent, FetchLibraryComponent // 移除所有服务类,仅保留组件、指令、管道 ], imports: [ BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }), HttpClientModule, FormsModule, RouterModule.forRoot([ { path: '', component: HomeComponent, pathMatch: 'full' }, { path: 'libraries', component: FetchLibrariesComponent }, { path: 'libraries/:id', component: FetchLibraryComponent }, ]) ], providers: [ CacheService, HttpClientService, LibraryService, // 替换为你的实际后端接口根地址 { provide: 'BASE_URL', useValue: 'https://你的后端接口根地址/' } ], bootstrap: [AppComponent] }) export class AppModule { }
修改完成后重新编译运行即可解决空对象引用和服务注册错误的问题。
内容的提问来源于stack exchange,提问作者James Fleming
相关产品推荐
相关产品推荐

