Angular2 DI - 在同一个构造函数中初始化多个不同的实例 [英] Angular2 DI - initializing multiple different instances in the same constructor

查看:20
本文介绍了Angular2 DI - 在同一个构造函数中初始化多个不同的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Angular2 DI 问题.假设我有一个 TestService 并且我想在同一个组件中使用该服务的 2 个不同实例.如果我只是向组件添加一个提供者,然后将 2 个实例添加到构造函数,我最终会得到相同的服务实例.例如:

I have an Angular2 DI question. Say I have a TestService and I want to use 2 different instances of this service inside the same component. If I simply add a provider to the component and I add the 2 instances to the constructor I end up with the same service instance. For example:

测试服务

import {Injectable} from "@angular/core";

@Injectable()
export class TestService {

    public id: number = Math.random();

    public toString(): string {
        return "Id: " + this.id;
    }
}

测试组件

import {Component, Input, OnInit} from "@angular/core";
import {TestService} from "../../services/test.service";

@Component({
    providers: [TestService]
})
export class TestComponent implements OnInit {

    constructor(private _testService1: TestService, private _testService2: TestService) { };

    ngOnInit() {
        console.log("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", this._testService1.toString());
        console.log("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", this._testService2.toString());
    }
}

控制台结果

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Id: 0.24242492129168425
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB Id: 0.24242492129168425

有人可以告诉我是否有办法使用 Angular2 的 DI 机制在同一个组件中注入多个不同的服务实例,或者我应该在这种特殊情况下放弃 DI 并使用手动构造函数手动创建我的实例吗?

Can someone pls tell me if there's a way to use Angular2's DI mechanism to inject multiple different instances of a service within the same component or should I just drop the DI for this particular case and create my instances manually with a manual constructor?

提前致谢

推荐答案

你可以注入一个工厂,每次调用都会返回一个新实例:

You can inject a factory that returns a new instance every time you call it:

@NgModule({
   providers: [{
      provide: 'testService', 
      useFactory: (/* TestService deps here like `http`*/) => 
        (/* params */) => new TestService(/* http */), 
      deps: [/* TestService deps here like `Http`*/ ]
    }]
})


@Component(...)
export class TestComponent implements OnInit {

    constructor(@Inject('testService') private _testServiceFactory) { };

    ngOnInit() {
        console.log("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", this._testServiceFactory( /* params */).toString());
        console.log("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", this._testServiceFactory().toString());
    }
}

Plunker 示例(点击按钮时检查浏览器控制台中的输出)

Plunker example (check the output in the browser console when you click the button)

这篇关于Angular2 DI - 在同一个构造函数中初始化多个不同的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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