Alexander Mills
Alexander Mills

Reputation: 99960

Share data between sibling components using non-singleton service

Using Angular, is there a way to share data between sibling components using a shared service, where that shared service is not a 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() {
  }

}

// the other sibling

@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() {
   }

}

// a helper class

export class Foo {

}

// the shared singleton service

@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();
  }

}

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?

Upvotes: 1

Views: 200

Answers (1)

Paritosh
Paritosh

Reputation: 11560

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();
 }
}

Use it in both components

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

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

Upvotes: 1

Related Questions