如何使用Angular DI注入声明的名称空间? [英] How can I inject a declared namespace with Angular DI?

查看:101
本文介绍了如何使用Angular DI注入声明的名称空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将pmn url node_module注入到我在Angular中的服务中。

I'm trying to inject the npm url node_module into my service in Angular.

我知道我可以做到:

import * as url from 'url';

并可以在我的课程中使用它,如下所示:

and can use it in my class as follows:

url.format(); //using it

尽管我想注入它,因为我相信我应该早点发现错误,

Although I want to inject it, since I believe I should catch errors sooner, by forcing all my classes to initialize with their dependencies in the constructor.

我知道我可以使用带接口的注入器令牌和useValue来注入简单值。

I know I can use injector Tokens with an interface and useValue to inject simple values.

interface MyInterface {
  property: string
}
const JS_PRETEND_TYPING = new InjectionToken<MyInterface>('small_desc');
const MY_VALUE = { a: 123 }

@NgModule({
  providers: [ { provide: JS_PRETEND_TYPING, useValue: MY_VALUE } ]
});

尽管url包具有输入内容,但声明为模块。

Although the url package has it's typing's declared as a module.

在url包中:

declare module "url" {
    export interface UrlObject { 
    ...
}

所以我不能这样做,因为我得到了错误:

So I can't do this because I get an error:

import * as url from 'url';


// ERROR: Cannot use namespace 'url' as a type. const
JS_PRETEND_TYPING_FOR_URL = new InjectionToken<url>('small_desc');

如何在我的Angular服务中注入'url'npm包?

How can I inject the 'url' npm package into my service in Angular?

import * as url from 'url';
class MyService {
   constructor(@Inject(JS_PRETEND_TYPING_FOR_URL) private url: url)
}


推荐答案

之所以会发生这种情况,是因为 url 不是一种类型。类具有与之关联的相同名称类型,但变量,函数和名称空间则没有。

This happens because url is not a type. Classes have types of same names associated with them, but variables, functions and namespaces don't.

应为:

constructor(@Inject(JS_PRETEND_TYPING_FOR_URL) private url: typeof url)

将DI用于库导入通常是过大的,除非已知它会以某种方式使它们受益(测试等)。如果是 url ,则没有任何意义。可以通过监视其方法进行测试。
不太可能需要通过DI交换它。

It is generally overkill to use DI for library imports, unless it's known that it will benefit them somehow (testing, etc). In case of url this doesn't make sense. It could be tested by spying on its methods. It's very unlikely that there will be a need to swap it with something else by means of DI.

这篇关于如何使用Angular DI注入声明的名称空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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