Home > front end >  subscribing for length of the list in angular
subscribing for length of the list in angular

Time:10-16

Imagine there are 2 components named component A and component B.

Let us say component B has list of items with addition and deletion functions. Assume that if component B has 0 items, then component A should display error message.

Note: Component A and component B do not appear on screen together. They have different routes.

Eg: localhost:4200/componenta, localhost:4200/componentb

So when component A is there, component B is not there and vice versa.

My doubt is "if component A and component B are not alive at the same time (i.e if both the components are not on the screen at the same time), will component A be able to subscribe to the current change in items length in component B?"

For the subscription to work, is it necessary that both component A and component B should be alive at the same time?

CodePudding user response:

Here we could use the rxjs BehaviorSubject in a service file. You could subscribe the public property in both component A and component B. Say if the value subscribed is null or undefined or empty array, then we could show the error message in component A and if length is greater than 0, then we could have the logic accordingly.

data.service.ts:

public data = new BehaviorSubject<any[]>(null);

component A:

public dataList: any[];
public constructor(
  private dataService: DataService
)

public ngOninit(): void{
  this.dataService.data.subscribe((list: any[])=>{
    this.dataList  = list;
    if(
       this.dataList == null || 
       this.dataList == undefined || 
       this.dataList?.length==0){
         // show error message
       }
  });
}

component B:

public dataList: any[];
public constructor(
  private dataService: DataService
)

public ngOninit(): void{
  this.dataService.data.subscribe((list: any[])=>{
    this.dataList  = list;        
  });
}

Here the logic would work even if both the component A and B are not loaded in the DOM together at the same time.

CodePudding user response:

To subscribe change when the component is not active or in DOM, you can use Behavior Subject. It will catch effect if app is still in DOM but component will render later.

  • Related