繁体   English   中英

Angular 7 - build --prod 失败并出现错误:无法解析所有参数

[英]Angular 7 - build --prod failed with error: Can't resolve all parameters for

我使用 Angular: 7.2.10 并且当我尝试使用命令构建用于生产的项目时:

ng b --prod

我有错误

ERROR in : Can't resolve all parameters for ApiService in ...

我有一个带有 3 个参数的构造函数的服务:

constructor(api: string, private _http: HttpClient, private httpUtils: HttpUtilsService) {
    this.api = `${api}/api`;        
  }

它由在 app.module.ts 定义的工厂实例化:

{      
      provide: ApiService,
      useFactory: apiHost,
      deps: [Store, HttpClient, HttpUtilsService]
    }

接口主机

export function apiHost(store: Store<RemoteConfig>, http: HttpClient, httpUtils: HttpUtilsService) {
  let item: string = localStorage.getItem(environment.apiHost);

  //store.pipe(select(backendApiHost), take(1)).subscribe(api => item = api); // Todo not always read val!
  //console.log('ss: ' + item);
  return new ApiService(item, http, httpUtils);
}

当我使用ng build它可以成功运行。

通过检查编译器发出的元数据来隐式解析依赖关系。 该元数据源自参数的类型。

在运行时,角度注入器会检查该信息以确定要注入哪些依赖项。 具体来说,它为每个相应的参数寻找一个注册的提供者。

由于您尚未注册映射到为string类型的参数发出的元数据的提供程序,因此查找失败并收到错误消息。 您可以为该类型注册一个提供程序,但鉴于字符串的使用范围如此广泛,这样做是不明智的。

然而,Angular 的依赖注入工具并不限于这种隐式解析。 使用Inject装饰器和InjectionToken的组合,您可以实现您的愿望。

api-token.ts

import {InjectionToken} from '@angular/core';

export const apiToken = new InjectionToken('api', {
  providedIn: 'root',
  value: 'myapi'
});

现在您可以使用此令牌请求为特定参数解析此依赖项。

数据服务.ts

import {Inject, Injectable} from '@angular/core';

import {apiToken} from './api-token';

@Injectable({providedIn: 'root'})
export class DataService {
   constructor(@Inject(apiToken) api: string) {}
}

Angular 找不到api: string的提供者。 实际上,您并没有注入 ApiService,而是在此处的代码中创建它: return new ApiService(item, http, httpUtils) ,因此您无需在提供程序中定义它。

我建议您从构造函数中删除 api 变量,将其传递给类方法,仅使用构造函数来传递注入。


    constructor(public _http: HttpClient) { }

getApi(api: string) {
    this._http.get(api).toPromise()
}

然后扩展你的 api 服务并在参数中传递 uri,我建议你也让 _http 公开,api 主机看不到私有 http,这些输入可能会导致构建产品失败

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM