2 years ago

#27819

test-img

Nesan Mano

Angular sharing data among other components not working properly

I am trying to use BehaviorSubject to share data between my components

Below is the code to my service

import {Injectable, Optional, SkipSelf} from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UrlService {
  private previousUrl: BehaviorSubject<any> = new BehaviorSubject(null);
  public previousUrl$: Observable<string> = this.previousUrl.asObservable();

  constructor(@Optional() @SkipSelf() parent?: UrlService) {
    if (parent) {
      throw Error(
        `[UrlService]: trying to create multiple instances,
        but this service should be a singleton.`
      );
    }
  }

  setPreviousUrl(previousUrl: string) {
    this.previousUrl.next(previousUrl);
  }

}

I have a first component in which I set the value as below. If I try to retrieve the value set in ngInit it works with the component.

constructor(private urlService:UrlService){
}

ngOnInit(): void {
this.urlService.setPreviousUrl(this.router.url.toString());
}

I have a second component in which I try to retrieve the value as below, I get null. I suspects that a different instances are created.

constructor(private urlService:UrlService){
}

ngOnInit(): void {
this.urlService.previousUrl$
  .subscribe((previousUrl) => {
    this.referer = previousUrl // it is always null
  });
}

angular

typescript

behaviorsubject

0 Answers

Your Answer

Accepted video resources