错误错误:未捕获(承诺):错误:StaticInjectorError(AppModule) [英] ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)
问题描述
我有以下代码:
import { Injectable } from '@angular/core';
@Injectable()
export class ClientCacheService {
private _cacheMode: CacheMode;
private _cacheMode: CacheMode;
constructor(cache?: CacheMode) {
if(!cache)
this._cacheMode = CacheMode.SessionStorage;
else
this._cacheMode = cache;
}
setToCache(key :string, prefix:string, definition: any) {
if(this._cacheMode === CacheMode.SessionStorage)
window.sessionStorage.setItem(`${prefix}_${key}`, JSON.stringify(definition));
else if(CacheMode.Memory)
window["`${prefix}_${key}`"] = JSON.stringify(definition);
}
getFromCache(key :string, prefix:string) {
let res = window.sessionStorage.getItem(`${prefix}_${key}`);
if (res) return JSON.parse(res);
return undefined;
}
}
export enum CacheMode{
Memory,
LocalStorage,
SessionStorage
}
当调用类ClientCacheService
的构造函数时,将显示以下消息:
When the constructor of the class ClientCacheService
is called, it is shown the following message:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[ClientCacheService -> Number]:
StaticInjectorError(Platform: core)[ClientCacheService -> Number]:
NullInjectorError: No provider for Number!
Error: StaticInjectorError(AppModule)[ClientCacheService -> Number]:
StaticInjectorError(Platform: core)[ClientCacheService -> Number]:
NullInjectorError: No provider for Number!
我在this._cacheMode = cacheMode;
行上放置了breakpoint
,调试器在到达此breakpoint
之前启动了错误.
I have put a breakpoint
on the line this._cacheMode = cacheMode;
and the debugger launches the error before reach this breakpoint
.
我不明白为什么会显示此错误.任何人都知道这意味着什么以及如何解决吗?
I'm not understanding why this errors is been shown. Any one have any idea what this means and how to solve it?
推荐答案
您正试图注入不可注入的枚举,您应该为Memory,LocalStorage和SessionStorage实现一个具有单个接口的抽象类,将其称为StorageService例如,接下来您应该像这样在构造函数中使用它:
You are trying to Inject enum that is not injectable, you should implement an abstract class with a single interface for Memory, LocalStorage and SessionStorage, Lets call it StorageService for example, next you should consume it in the constructor like this:
constructor(storageService: StorageService) {}
最后是providers数组
finally the providers array
providers: [
{ provide: StorageService, useClass: Memory} // or LocalStorage or SessionStorage
]
这篇关于错误错误:未捕获(承诺):错误:StaticInjectorError(AppModule)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!