27

我创建了 AngularJS 2 服务并在 2 个不同的组件中使用它:App-Component & Sub-Component。我的服务的每个输出属性“日志”(一个字符串)。

状态服务类:

@Injectable ()
class StateService {

    public log : string;
    static count : number = 0;

    constructor () {
        this.log = '';
        StateService.count++;
        this.writeToLog ('CREATED '+StateService.count+' at ' + new Date().toString());
    }

    public writeToLog (text : string) : void {
        this.log += text + '\n';
    }
}  

零件 :

@Component ({
    selector : 'Sub-Component',
    template : `<hr>
            This is the Sub-Component !
            <BR>
            StateService Log : 
            <pre>{{ _stateService.log }}</pre>
            <button (click)="WriteToLog ()">Write to log</button>
            `,
    providers : [StateService]
})

export class SubComponent {
    constructor (private _stateService : StateService) {
    }

    public WriteToLog () : void {
        this._stateService.writeToLog ('From Sub-Component - This is '+new Date().toString());
    }
}

代码的实时示例here

我除了该服务创建一次并且当每个组件调用 WriteToLog 方法时,每个组件的输出都是相同的,但事实并非如此。

输出示例:

App-Component 可以输出这个:

实例 1 - 创建于 2016 年 1 月 21 日星期四 11:43:51

来自 App-Component - 这是 2016 年 1 月 21 日星期四 11:43:54

来自 App-Component - 这是 2016 年 1 月 21 日星期四 11:43:55

子组件可以输出这个:

实例 2 - 创建于 2016 年 1 月 21 日星期四 11:43:51

来自子组件 - 这是 2016 年 1 月 21 日星期四 11:43:57

来自子组件 - 这是 2016 年 1 月 21 日星期四 11:43:58

因此,似乎创建了 2 个服务实例(实例 1 + 实例 2)

我只想要一个实例;)当我在日志中附加字符串时,它必须出现在两个组件中。

谢谢您的帮助

4

2 回答 2

32

更新 Angular >= 2.0.0-RC.6

不要将服务添加到组件的提供者。而是将其添加到

@NgModule({ providers: [...], ...

(由于延迟加载的模块引入了自己的作用域而不是延迟加载的模块)

@Component ({
    selector : 'Sub-Component',
    template : `<hr>
            This is the Sub-Component !
            <BR>
            StateService Log : 
            <pre>{{ _stateService.log }}</pre>
            <button (click)="WriteToLog ()">Write to log</button>
            `,
    // providers : [StateService] <== remove
})

角度 <=2.0.0-RC.5

如果您将它添加到组件上,您将获得每个组件实例的新服务实例。而是将其添加到

bootstrap(AppComponent, [StateService]);

您可以通过将其添加到单个组件来获得更细粒度的控制,然后该组件和所有子组件都会注入相同的实例,否则应用程序将使用由bootstrap(). 这是 Angulars DI 中的“层次结构”。

另见
- http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html
- http://blog.thoughtram.io/angular/2015/09/17 /resolve-service-dependencies-in-angular-2.html

于 2016-01-21T16:55:30.647 回答
3

除了 Günter 的出色答案之外,此链接也许可以提供有关 Angular2 的分层依赖注入如何工作的更多详细信息:

于 2016-01-21T17:03:29.557 回答