typescript - Angular2 - 使用服务在组件之间共享数据

标签 typescript angular angular2-services

我有一个对象,我想在我的组件之间共享到 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 之前被填充了。

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

我错过了什么?

谢谢

已解决

我的问题是我注入(inject)了我的 ConfigService 两次。在应用程序的 Bootstrap 和我正在使用它的文件中。

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

最佳答案

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

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

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

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

bootstrap(AppComponent, [ ConfigService ]);

要理解为什么需要这样做,您需要了解 Angular2 的“分层注入(inject)器”功能。以下链接可能会有用:

关于typescript - Angular2 - 使用服务在组件之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35273106/

相关文章:

reactjs - React + Redux-Observable + Typescript - 编译,参数不可分配错误

没有不可变对象(immutable对象)的推送 Angular 变化检测策略

在使用@input() 传递数据之前加载 Angular 2 子组件

Angular2 ExpressionChangedAfterItHasBeenCheckedError 错误

Angular 2 组件因添加空服务而中断

javascript - 如何在 JavaScript 中计算数组的总和

Typescript 需要参数来匹配第一个参数的类型签名

Angular 2 @Input 经常被调用

javascript - 使用 useParams 从 url 获取值

显然跳过了 Docker 内部生产的 Angular 构建