【问题标题】:Cannot inject InjectionToken to service constructor无法将 InjectionToken 注入服务构造函数
【发布时间】: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_URL in client.ts 并且不要两次声明相同的令牌
  • 非常感谢,解决了我的问题。
  • 我应该在哪里导入它我正在经历这个错误
  • 只是在某处放置注入令牌的定义并在需要的地方导入

标签: angular typescript swagger swagger-codegen


【解决方案1】:

在您的environment.ts 文件中,您应该为API_BASE_URL 添加一个条目,如下所示:

export const environment = {
  production: false,
  API_BASE_URL: "https://localhost:44336"
};

同样在您的environment.prod.ts 中为您的生产添加一个条目API_BASE_URL

接下来在您的main.ts 文件中,从您的client.ts 中导入API_BASE_URL 声明并将API_BASE_URL 添加到提供程序中,以便您的main.ts 看起来如下所示:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { environment } from './environments/environment';
import { AppModule } from "./app/app.module";
import { API_BASE_URL } from "./app/client.ts";

console.log(environment);

if (environment.production) {
  enableProdMode();
}

export function getBaseUrl() {
  return document.getElementsByTagName('base')[0].href;
}

const providers = [
  { provide: API_BASE_URL, useValue: environment.API_BASE_URL },
  { provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
];

platformBrowserDynamic(providers).bootstrapModule(AppModule)
  .catch(err => console.error(err));

【讨论】:

    猜你喜欢
    • 2014-03-29
    • 2022-01-02
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多