28

我有一个我想在我的组件之间共享到 Angular2 应用程序中的对象。

这是第一个组件的来源:

/* app.component.ts */

// ...imports
import {ConfigService} from './config.service';

@Component({
    selector: 'my-app',
    templateUrl: 'app/templates/app.html',
    directives: [Grid],
    providers: [ConfigService]
})
export class AppComponent {
    public size: number;
    public square: number;

    constructor(_configService: ConfigService) {
        this.size = 16;
        this.square = Math.sqrt(this.size);

        // Here I call the service to put my data
        _configService.setOption('size', this.size);
        _configService.setOption('square', this.square);
    }
}

第二个组成部分:

/* grid.component.ts */

// ...imports
import {ConfigService} from './config.service';

@Component({
    selector: 'grid',
    templateUrl: 'app/templates/grid.html',
    providers: [ConfigService]
})
export class Grid {
    public config;
    public header = [];

    constructor(_configService: ConfigService) {
        // issue is here, the _configService.getConfig() get an empty object 
        // but I had filled it just before
        this.config = _configService.getConfig();
    }
  }

最后是我的小服务 ConfigService:

/* config.service.ts */

import {Injectable} from 'angular2/core';

@Injectable()
export class ConfigService {

    private config = {};

    setOption(option, value) {
        this.config[option] = value;
    }

    getConfig() {
        return this.config;
    }
}

我的数据没有共享,在grid.component.ts中,该_configService.getConfig()行返回一个空对象,但它是在app.component.ts之前填充的。

我阅读了文档和教程,没有任何效果。

我错过了什么?

谢谢

解决了

我的问题是我两次注入了我的 ConfigService。在应用程序的引导程序和我使用它的文件中。

我删除了providers设置并且它起作用了!

4

3 回答 3

28

您在两个组件中定义它。所以服务是不共享的。您有一个AppComponent组件实例和另一个组件实例Grid

@Component({
  selector: 'my-app',
  templateUrl: 'app/templates/app.html',
  directives: [Grid],
  providers: [ConfigService]
})
export class AppComponent {
  (...)
}

快速的解决方案是删除providersGrid 组件的属性...这样服务实例将AppComponent由其及其子组件共享。

另一种解决方案是在函数中注册相应的提供者bootstrap。在这种情况下,实例将由整个应用程序共享。

bootstrap(AppComponent, [ ConfigService ]);

要了解为什么需要这样做,您需要了解 Angular2 的“分层注入器”特性。以下链接可能有用:

于 2016-02-08T15:22:19.733 回答
6

对于最新版本的 angular,如果要共享服务,不能将其添加到 bootstrap 函数中。只需像使用普通服务一样将其添加到 NgModule 提供者列表中,它的默认行为将是单例的。

引导程序(应用程序组件);

@NgModule({
    declarations: [
        ....
    ],
    imports: [
       ....     
    ],
    providers: [
        ConfigService,
....
于 2016-10-18T21:53:23.967 回答
4

不要添加ConfigServiceproviders您的组件中。这会为每个组件生成新实例。将其添加到providers公共父组件中。如果您将它添加到您的根组件或bootstrap(App, [ConfigService])您的整个应用程序共享一个实例。

于 2016-02-08T15:23:27.917 回答