Home > front end >  variable capture behaviorsubject angular services
variable capture behaviorsubject angular services

Time:11-30

I have a problem with behaviorSubjects in angular

let's describe a problem with sample codes

I have a service like this

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

CodePudding user response:

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.

CodePudding user response:

Services declared in the module are shared between all components in the module. If you want private instances of the service, you need to declare it as a provider for the component itself.

Something like:

@Component({
  selector: 'app-a',
  templateUrl: './a.component.html',
  providers: [ DataService ]
})
  • Related