加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:46:26 所属栏目:安全 来源:网络整理
导读:我有一个对象,我想在我的组件之间共享一个Angular2应用程序. 这是第一个组件的来源: /* app.component.ts */// ...importsimport {ConfigService} from './config.service';@Component({ selector: 'my-app',templateUrl: 'app/templates/app.html',directi
我有一个对象,我想在我的组件之间共享一个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两次.在应用程序的引导和在我使用它的文件中.

我删除了提供者的设置和它的工作!

您可以在两个组件中定义它.所以服务不共享.您有一个AppComponent组件实例,另一个用于Grid组件.
@Component({
  selector: 'my-app',providers: [ConfigService]
})
export class AppComponent {
  (...)
}

快速的解决方案是删除提供者属性到您的网格组件…这样,服务实例将被AppComponent及其子组件共享.

另一个解决方案是在引导功能中注册相应的提供者.在这种情况下,实例将被整个应用程序共享.

bootstrap(AppComponent,[ ConfigService ]);

要理解为什么需要这样做,您需要注意Angular2的“分层注射器”功能.以下链接可能会有用:

> What’s the best way to inject one service into another in angular 2 (Beta)?
> https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读