Angular 2,如何使用服务在组件之间共享数组数据? [英] Angular 2, How to Share Array Data Between components using service?

查看:191
本文介绍了Angular 2,如何使用服务在组件之间共享数组数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular2中,使用服务在组件之间共享数组数据吗?

In Angular2, Share Array data between components using service?

我设计的结构如下.

I'm designed this structure like below.

object structure
{
    data: 'data'
    keys: ['key1', 'key2', ... , 'keyN']
}

* Service has a array of total objects.
totalObject = [object1, object2, ... , objectN]

首先,我像这样初始化服务的selectedObject.

At first I initialized selectedObject of service like this.

selectedObject = totalObject;

然后我像这样在构造函数上初始化组件B的selectedObject.

Then I initialized selectedObject of Component B on constructor like this.

constructor(private wordService: WordService) {
     this.words = wordService.selectedWords;
}

首先,组件B正确显示了所有对象! 但是,当服务将新数组初始化为selectedObject时,组件B无法显示所选对象.

At the first, Component B displayed All objects correctly!! But, when the service initialize new array to selectedObject, Component B cannot display selected objects.

 // It's not working...
 // remove
this.selectedWords.splice(0, this.selectedWords.length);

// add
for(let i in WORDS) {
  if(WORDS[i].keys.indexOf(key) >= 0) {
    this.selectedWords.push(WORDS[i]);
  }
}

推荐答案

您可以简单地创建一个服务并将其用作单个"服务.

You can simply create a service and use it as a "singleton" service.

@Injectable()
export class DataService {

  public selectedWords:string[] = [];
}

然后将其提供给应用程序的顶层,这样一来,整个应用程序将只使用一个实例:

And you provide it at the top level of your application, this way only one instance will be used across your app:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, OtherComponent ],
  bootstrap: [ App ],
  providers: [ DataService ]
})
export class AppModule {}

Plunkr示例

这篇关于Angular 2,如何使用服务在组件之间共享数组数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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