javascript - Angular 2注入(inject)全局依赖

标签 javascript dependency-injection typescript angular

我想做的是在每个组件中都有一个可用的服务,但我宁愿不必将它导入到所有组件中。 (显然,如果必须的话,我会的。)

我想,也许是错误的,我可以做一些类似于我在我的应用程序中引导 HTTP_PROVIDERS 的事情,这使得它可用于 HTTP(如果我没记错的话,这是必需的)。

例如,在我的 app.ts 文件中:

import { bootstrap } from 'angular2/platform/browser';
import { Injectable } from 'angular2/core';
import { HTTP_PROVIDERS } from 'angular2/http';
import 'rxjs/add/operator/map';
import { WidgetService } from './widget.service';
import { BuilderComponent } from './modules/builder/builder.component';

bootstrap(BuilderComponent, [HTTP_PROVIDERS, WidgetService]);

我希望这将使 WidgetService 在所有子/孙组件等组件中可用。 (BuilderComponent 是一个有多个子/孙子的父组件。)

我在使用@Inject 注入(inject)时遇到的错误,而@Injectable 未在服务本身中使用:

Uncaught ReferenceError: WidgetService is not defined

在服务中使用@Injectable,而不是使用@Inject注入(inject)时的错误:

Cannot resolve all parameters for 'MyComponent'(NonGlobalService, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'MyComponent' is decorated with Injectable.

我不确定为什么 MyComponent 需要用 Injectable 装饰,但是当我用 @Injectable 装饰它时我得到了同样的错误。

widget.service.ts

import { Injectable, NgZone } from 'angular2/core';

@Injectable()
class WidgetService {
    constructor(private _zone: NgZone) {
    }
    // other methods here...
}

export { WidgetService };

以及我如何尝试注入(inject)它:

class MyComponent {
    constructor(private _nonGlobalService: NonGlobalService,
                private _widget: WidgetService) {
    }
}

总结:

  1. 您能否在全局范围内将服务注入(inject)所有组件,而无需手动将其导入每个组件? (即:如果我需要,可以随处使用。)
  2. 如果可以,有人可以解释我做错了什么,并告诉我如何正确地做。
  3. 感谢您抽空回答!

最佳答案

有不同的方法。

您可以创建一个包装器服务并只注入(inject)这个服务。

@Injectable()
export class FooService {
  doFoo() {...};
}

@Injectable()
export class BarService {
  doBar() {...}
}

@Injectable()
export class GlobalService {
  constructor(public foo:FooService, public bar:BarService) {
  }
}

这里需要导入GlobalService

export class MyComponent {
  constructor(global:GlobalService) {
    global.foo.doFoo();
    global.bar.doBar();
  }
}

这样你就不需要为组件导入任何东西

bootstrap(AppComponent, [
    provide('foo', { useClass: FooService }), 
    provide('bar', { useClass: BarService })]);

export class MyComponent {
  constructor(@Inject('foo') foo, @Inject('bar') bar) {
    foo.doFoo();
    bar.doBar();
  }
}

但我不认为第二种方法是可取的。您不会获得任何 IDE 支持,因为服务的类型在 MyComponent 中未知。

关于javascript - Angular 2注入(inject)全局依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35298903/

相关文章:

javascript - 替换字符串 Jquery

尝试获取打开页面的设备的 IP 地址时,Javascript 页面不工作

javascript - 带 Angular 2 RC1 的日期选择器

c# - 在 C# 中使用 DI 登录到控制台

javascript - AngularJS - DI 系统如何知道参数的名称?

typescript - 为什么以下 TypeScript 程序不会抛出类型错误?

typescript - 如何在我的 Typescript React Native 项目中获取 fetch 函数的类型定义?

javascript - 创建 Backbone 模型的副本

c# - 没有依赖服务的 DI 服务

typescript - 我可以在 Typescript 中创建一个类 [] 运算符吗