title: How can I create a variable in a service that gets its data from a promise yet is shared between two components?
body: <p>I have a service in an Angular 2 using TypeScript. I want to be able to share an array of values that I get from that service. when one component makes a change to the array I need it to be reflected in another component. </p>
  
  <p>This is the basics of my service and the object it uses</p>
  
  <pre><code>export class deviceObj {
    device_Id:number;
    deviceGroup_Id:number;
    name:string;
    favoriteFlag:boolean;
    visibleFlag:boolean;
  
  }
  
  export class Favorite {
      favorite_Id: number;
      device: deviceObj;
      constructor(){this.device = new deviceObj()};
  
  }
  
  
  @Injectable()
  export class FavoriteService {
      private headers = new Headers({'Content-Type': 'application/json'});
      private favoritesURL = 'URL THAT FEETCHES DATA';
      favorites: Favorite[];
      constructor(private http: Http) {
  
      this.getFavorites().then(favorites =&gt; this.favorites = favorites);
  
  }
  
  getFavorites(): Promise&lt;Favorite[]&gt; {
      return this.http.get(this.favoritesURL).toPromise().then(response =&gt; response.json() as Favorite[]).catch(this.handleError);
  
  
  }
  
  protected handleError2(error: Response) {
      console.error(error);
      return Observable.throw(error.json().error || 'server error');
  }
  
  private handleError(error: any): Promise&lt;any&gt; {
      console.error('An error occurred', error); // 
      return Promise.reject(error.message || error);
  }
  
  
  }
  </code></pre>
  
  <p>And here is one of the components that gets the array of favorites.</p>
  
  <pre><code> import {FavoriteService} from'../../services/favorite/favorite.service';
  declare var jQuery: any;
  
  @Component({
    selector: '[sidebar]',
    directives: [
      ROUTER_DIRECTIVES,
      SlimScroll
    ],
    template: require('./sidebar.html')
  })
  
  export class Sidebar implements OnInit {
  
  
    constructor(config: ConfigService, el: ElementRef, router: Router, location: Location,
    private favoriteService:FavoriteService) {
  
    }
  getFavorites(): void{
      this.favoriteService
          .getFavorites()
          .then(favorites =&gt; this.favorites = favorites);
  
  }
  </code></pre>
  
  <p>In each component that uses the service it has its own favorites array that gets assigned on load. However I want a singleton variable in the service where changes can be reflected in two components. I'm not sure how to do this with promises. I am happy to clarify further if needed. Any help would greatly be apreciated.</p>