使用非单例服务在同级组件之间共享数据 [英] Share data between sibling components using non-singleton service

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

问题描述

使用Angular,有没有一种方法可以使用共享服务在同级组件之间共享数据,而该共享服务不是单例?

Using Angular, is there a way to share data between sibling components using a shared service, where that shared service is not a singleton?

我想到的唯一方法是注入 singleton 服务,然后在该singleton服务中使用哈希映射来引用其他类实例.

The only way I can think of doing that is injecting a singleton service, and then using a hashmap in that singleton service to reference other class instances.

@Component({
  templateUrl: './sibling.component.html',
  styleUrls: ['./sibling.component.scss'],
})

export class Sibling1Component implements OnInit {

  displayMode: string = 'default';
  foo: Foo;


  constructor(private s: SharedSingletonService) {

    // I need to pass an id, but how
    this.foo = s.getInstanceOfFoo('some-uuid');

  }

  ngOnInit() {
  }

}

//另一个兄弟姐妹

@Component({
  templateUrl: './sibling.component.html',
  styleUrls: ['./sibling.component.scss'],
})

export class Sibling2Component implements OnInit {

  displayMode: string = 'default';
  foo: Foo;


  constructor(private s: SharedSingletonService) {

     // I need to pass an id, but how
     this.foo = s.getInstanceOfFoo('the-same-uuid-as-above');

  }

   ngOnInit() {
   }

}

//辅助类

export class Foo {

}

//共享单例服务

@Injectable()
export class SharedSingletonService {

  foos : <{[key:string]:Foo}> = {}

  constructor(){

  }

  getInstanceOfFoo(id){
    if(this.foos[id]){
       return this.foos[id];
     }

    return this.foos[id] = new Foo();
  }

}

所以主要问题是-如何在同级组件实例中使用相同的ID,以便可以在共享服务中查找foo的相同实例?

so the main question is - how can I use the same id in the sibling component instances, so that I can look up the same instance of foo in the shared service?

推荐答案

如果您的目的只是共享服务的ID ...
创建另一个服务,

If your motive is just to share the id for the service...
Create another service,

import * as uuid from 'uuid';

@Injectable()
export class IdSharerService {

 id: string;

 constructor(){
     id = uuid.v4();
 }
}

在两个组件中都使用

constructor(private idSvc IdSharerService, private sharedSvc: SharedSingletonService )
{       
   this.foo = s.getInstanceOfFoo(idSvc.id);
}

希望这会有所帮助.您可以使用此NPM软件包生成uuid: https://www.npmjs.com/package/uuid

Hope this helps. You can use this NPM package to generate uuid: https://www.npmjs.com/package/uuid

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

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