How to subscribe localstorage in angular 7

Viewed 2629

I want to communicate between parent and child tabs. I will get some data in child tab (different component then parent) and then send this data to parent. I think that using browser localstorage is right way. So I'm insert data to localstorage and want that parent component automatically absorb this change, get data from localstorage and close child window.

I have 2 components for parent and child windows and one service for subscribe localstorage. Problem is that parent component did not see changes because I am changing subject with "next" from child one.

service code is:

export class ObserveLocalStorageService {
  private storageSub= new Subject<any>();

  watchStorage(): Observable<any> {
    return this.storageSub.asObservable();
  }

  setItem(key: string, data: any) {
    localStorage.setItem(key, data);
    this.storageSub.next('changed');
  }

  removeItem(key) {
    localStorage.removeItem(key);
    this.storageSub.next('changed');
  }
}

child component code is:

export class FbLoginPopupComponent implements OnInit {

     uriObject: any;

     constructor(private storageService: ObserveLocalStorageService, 
                 private activatedRoute: ActivatedRoute) {}

     ngOnInit() {
       this.activatedRoute.fragment.subscribe((fragment: string) => {
         console.log('My hash fragment is here => ', fragment);

         this.uriObject = JSON.parse('{"' + decodeURI(fragment)
           .replace(/"/g, '\\"')
           .replace(/&/g, '","')
           .replace(/=/g,'":"') + '"}');


         if (this.uriObject['access_token']) {
           this.storageService.setItem('fb_tk', true);
           this.storageService.setItem('fb_tk_is', this.uriObject['access_token']);
         } else {
           this.storageService.setItem('fb_tk_err', this.uriObject['error']);
           this.storageService.setItem('fb_tk_err_desc', this.uriObject['error_description']);
         }
     }
}

Finally my parent component looks like:

export class FacebookLoginComponent implements OnInit, OnDestroy {

  private authWindow: Window;     

  constructor(private storageService: ObserveLocalStorageService) {}

  ngOnInit() {
     this.storageService.watchStorage().subscribe((data: string) => {
       console.log(data); <------------------ **problem is here. data is not loging**
     });

  launchFbLogin() {
    this.authWindow = window.open('https://www.facebook.com/v2.11/dialog/oauth?' +
      '&response_type=token' +
      '&display=popup' +
      '&client_id=123321123321123321123321' +
      '&display=popup' +
      '&redirect_uri=https://localhost:44312/auth/fb-login-popup' +
      // '&redirect_uri=https://localhost:44312/facebook-auth.html' +
      '&scope=email',null,'width=600,height=400');
  }

}

I can not find solution. Please help.

Thank you

0 Answers
Related