How can I use same instance of an angular service between components in different windows?

Viewed 209

I have a component mainComponent which calls for a service myService to http request some data update a BehaviorSubject data. Once the request is complete, a new window opens with component otherComponent that will display some info from myService.data.

However, otherComponent does not receive the newest value from data - it receives whatever data is initially set to.

mainComponent.ts

open() {
    this.myObs = this.myService
    .fetchObservable()
    .subscribe(() => {
        this.myService.data.subscribe(value => {
            console.log(value) //logs "new data"                
        });
        this.nativeWindow.open('workflow-editor'); //occurs after data has been updated
    })

myService.ts

public data: BehaviorSubject<string> = new BehaviorSubject<string>("old data");
    fetchObservable(){
        return this.http.get('./url')
        .pipe(
            map(res => {
                this.data.next("new data");
                console.log(this.data.value) //console.logs "new data"
                return res;
            })
        )
    }

otherComponent.ts

ngOnInit(){
        this.myService.data.subscribe(value => {
            console.log(value) //console.logs "old data"
        });

This problem only occurs when I load otherComponent in a new window. When I load the component in the same window, it correctly logs "new data". I suspect this is because a new window loads a new version of the app, thus creating a new instance of of myService - one that hasn't had its data value updated.

Is there any way around this? Can I use the same instance of a service in two windows?

1 Answers

Sounds like a job for localStorage

Write a service which can update the localstorage and also get the values. Something similar to the below snippet.

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

@Injectable()
export class LocalStorageService {

  constructor() { }

  setLocalStorage(key, value) {
    localStorage.setItem(key, JSON.stringify(value));
  }

  getLocalStorage(key) {
    return JSON.parse(localStorage.getItem(key));
  };
}

Using this the data will be available between windows. As you said, a new angular app instance is created when a new window is opened so the service data is reset, so you can workaround the data loss using localStorage. Below is a working example!

Stack Blitz Demo

Reference: Storing data across windows

Related