Let's say I want to share an object between multiple components. This service will allow components to send or receive the object.

This functionality allows for an object to be Globally Accessible. The service should also allow multiple global objects and a way to unsubscribe.

The full example is here.

import { Injectable } from '@angular/core';
import { 
  Subscription } from 'rxjs';

export class GlobalService {
  private subjects: object = {};

  subscribe<T>(key:string, fn: (value: T) => void, unsubscribe: Subject<any>): Subscription {
    return this.subjects[key]
               .subscribe({ next: fn });

  emit<T>(key: string, value: T): void {

  private putSubject<T>(key: string): void {
    if (!this.subjects[key]) {
      this.subjects[key] = new BehaviorSubject<T>(null);

Any comments are welcome!

  • \$\begingroup\$ This is not a complete code. The context is missing. The intent is unclear. Please improve your question so that it can be reviewed. "Service that shares an object" is too abstract. \$\endgroup\$ – Igor Soloydenko May 10 '18 at 5:49
  • \$\begingroup\$ I am sorry but this update still does not say what kind of object this service deals with. What the application is doing. This code is abstract "service-based data sharing". It can be "right"; it can be "wrong". Without knowing the real usage of the service and the real hierarchy of components in your particular business problem, it can not be reviewed. \$\endgroup\$ – Igor Soloydenko May 10 '18 at 19:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.