无法将InjectionToken注入服务构造函数

时间:2019-01-05 12:44:21

标签: angular typescript swagger swagger-codegen

我需要解决为什么不将我的injectionToken注入类构造函数中。我有角(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!

1 个答案:

答案 0 :(得分:0)

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

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

同样,在您的environment.prod.ts中,为您的作品API_BASE_URL添加一个条目。

接下来,在您的main.ts文件中,从API_BASE_URL导入client.ts声明,并将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));