Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

variable capture behaviorsubject angular services

I have a problem with behaviorSubjects in angular

let’s describe a problem with sample codes

I have a service like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export class DataService {
   private _data$ = new BehaviorSubject<any[]>([]);

   public get data() {
      return this._data$.asObservable();
   }

   getDataFromServer() {
     this.http.get(...).subscribe((res) => {
        this._data$.next(res)
    })
   }
}

and also i had two component like this

export class componentA {
  
  data : any[] = []

  constructor(private dataService:DataService) {}

  ngOnInit() {
    this.dataService.data.subscribe((res) => {
      this.data = res
    })
  }
}

export class componentB {

  data :any[] = []

  constructor(private dataService:DataService) {}

  ngOnInit() {
    this.dataService.data.subscribe((res) => {
      this.data = res
    })
  }
}

and display data Array in the template in both component my problem is when i change data of the behaviorSubject from componentB the data changed in componentA and i want they have different instance of behaviorSubject

>Solution :

I believe that what you want to achieve is not related using BehaviourSubject.

What you could do is to provide your service on each component like this:

Component A:

@Component({
  selector: '...',
  templateUrl: '...',
  styleUrl: ['...'],
  providers: ['MyService'] 
})
export class ComponentA

ComponentB

@Component({
  selector: '...',
  templateUrl: '...',
  styleUrl: ['...'],
  providers: ['MyService'] 
})
export class ComponentB

Each component has a different instance of your service, if component B makes some changes in the service, component A will not be aware of those changes, and the other way around too, B is not aware of the changes being made from A

Ideally, you would want to have the same instance of your service available in your whole app but, this way is also a valid one.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading