【发布时间】:2019-01-05 12:44:20
【问题描述】:
我需要解决,为什么我的 injectionToken 没有被注入到类构造函数中。我有 Angular (7.1),从 NSwag 生成的代码。
我已经尝试将提供程序代码放在模块和组件中。感谢您的建议。
client.ts
export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');
export class Client implements IClient {
private http: HttpClient;
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
// Removed @Optional for debug purpose
constructor(@Inject(HttpClient) http: HttpClient, @Inject(API_BASE_URL) baseUrl?: string) {
this.http = http;
this.baseUrl = baseUrl ? baseUrl : "";
}
}
app.module.ts
const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');
// providers array
providers: [
{provide: API_BASE_URL, useValue: 'localhost:1234'},
Client,
ArticleService
]
article.service.ts
@Injectable({
providedIn: 'root'
})
export class ArticleService {
client: Client;
constructor(client: Client) {
this.client = client;
}
}
ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)
[Client -> InjectionToken API_BASE_URL]:
StaticInjectorError(Platform: core)[Client -> InjectionToken API_BASE_URL]:
NullInjectorError: No provider for InjectionToken API_BASE_URL!
Error: StaticInjectorError(AppModule)[Client -> InjectionToken API_BASE_URL]:
StaticInjectorError(Platform: core)[Client -> InjectionToken API_BASE_URL]:
NullInjectorError: No provider for InjectionToken API_BASE_URL!
【问题讨论】:
-
您应该从
client.ts导入API_BASE_URLinclient.ts并且不要两次声明相同的令牌 -
非常感谢,解决了我的问题。
-
我应该在哪里导入它我正在经历这个错误
-
只是在某处放置注入令牌的定义并在需要的地方导入
标签: angular typescript swagger swagger-codegen