问题
I have the following code:
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
}
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!
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?
回答1:
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) {}
finally the providers array
providers: [
{ provide: StorageService, useClass: Memory} // or LocalStorage or SessionStorage
]
来源:https://stackoverflow.com/questions/51267560/error-error-uncaught-in-promise-error-staticinjectorerrorappmodule