Angular 7-build --prod失败,并出现以下错误:无法解析所有参数 [英] Angular 7 - build --prod failed with error: Can't resolve all parameters for

查看:186
本文介绍了Angular 7-build --prod失败,并出现以下错误:无法解析所有参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use Angular: 7.2.10 and when I try to build project for production with command:

ng b --prod

我出错了

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

我为带有3个参数的构造函数提供服务:

I have service with a constructor with 3 params:

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

通过在app.module.ts上定义的工厂实例化:

Which instantiates by factory defined at app.module.ts:

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

apiHost

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时,它可以成功工作.

When I use ng build it works successfully.

推荐答案

通过检查编译器发出的元数据可以隐式解决依赖关系.该元数据是从参数的类型派生的.

Dependencies are implicitly resolved by examining the metadata emitted by the compiler. This metadata is derived from the types of the parameters.

在运行时,角度喷射器检查该信息以确定要喷射的依赖项.具体来说,它会为每个对应的参数寻找注册的提供程序.

At runtime, the angular injector inspects that information to determine which dependencies to inject. Specifically, it looks for a registered provider for each corresponding parameter.

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

Since you haven't registered a provider that maps to the metadata emitted for a parameter of type string the lookup fails and you receive an error. You could register a provider for that type but it would not be wise to do so given just how broadly strings are used.

但是,Angular的依赖项注入工具不限于此隐式解决方案.结合使用Inject装饰器和InjectionToken,可以实现您想要的.

However, Angular's dependency injection facilities are not limited to this implicit resolution. Using a combination of the Inject decorator and InjectionTokens you can achieve what you wish.

api-token.ts

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

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

现在,您可以使用此令牌请求为特定参数解决此依赖性.

Now you can use this token to request that this dependency is resolved for a specific parameter.

data.service.ts

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

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

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

这篇关于Angular 7-build --prod失败,并出现以下错误:无法解析所有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆