我一直对 JIT and AoT compilers 之间的不一致有一些疑问。 .最近困扰我的错误是 Error: Can't resolve all parameters for IndexedDBCache
. IndexedDBCache 是一项依赖于 string
的服务参数:
请注意,当我删除“protected”属性时也会出现此问题!
// indexeddb-cache.ts
import { Injectable } from '@angular/core';
@Injectable()
export class IndexedDBCache {
constructor(protected databaseName : string) {}
}
我正在使用工厂来提供服务的版本:
// test-api.cache.factory.ts
import { IndexedDBCache } from '../indexeddb-cache/indexeddb-cache';
export function testIndexedDBCacheFactory() { return new IndexedDBCache('test'); }
// test-api.cache.ts
import { InjectionToken, Provider } from '@angular/core';
import { IndexedDBCache } from '../indexeddb-cache/indexeddb-cache';
import { testIndexedDBCacheFactory } from './test-api.cache.factory';
export const testIndexedDBCache = new InjectionToken<IndexedDBCache>('testIndexedDBCache');
export let testIndexedDBCacheProvider : Provider = {
provide: testIndexedDBCache,
useFactory: testIndexedDBCacheFactory
};
注意:必须根据 func-in-providers-useFactory 拆分这些文件和 arrow-function-exports - 不要问我为什么 =/
现在 AoT 编译器不喜欢这个 string
参数。我调查了这个问题,但只能找到对 OpaqueToken
的引用(现在被描述并替换为 InjectionToken<string>
)。我的代码现在应该是:
// test-api.cache.factory.ts
import { InjectionToken } from '@angular/core';
import { IndexedDBCache } from '../indexeddb-cache/indexeddb-cache';
const testIndexedDBCacheFactoryToken = new InjectionToken<string>('test');
export function testIndexedDBCacheFactory() { return new IndexedDBCache(testIndexedDBCacheFactoryToken); }
显然这不是编译,因为构造函数只允许 string
范围。我对 InjectionTokens 或手头的 AoT 问题没有足够的了解来解决这个问题 - 有人对可行的结构有什么建议吗?
有关我的代码和问题的更多上下文,请访问 angular/angular#17295 .
我尝试过的事情:
- 删除
protected
访问修饰符 > 仍然存在完全相同的错误 - 删除字符串参数> 不是一个选项 - 它定义了服务
- 用
InjectionToken<string>
替换工厂中的字符串参数> InjectionToken 不是合适的参数
最佳答案
对手头的问题存在误解。要工厂化的类本身不是服务,因此不需要 @Injectable
属性。更多详细信息,请访问 Creating AoT compatible Service Factories
关于angular - 为 AoT 编译标记化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44432641/