Home > OS >  Multiple slide outs using the same service
Multiple slide outs using the same service

Time:08-13

I have created a data service which is used to toggle my slide out. I want to reuse the service for multiple slide outs but I'm unsure how to do so. Here is what I have so far.

data-share.service.ts

private slideoutSource = new BehaviorSubject<boolean>(true)
slideoutStatus$ = this.slideoutSource.asObservable();

toggleSlideout() {
   const slideoutSource = this.slideoutSource.value;
   this.slideoutSource.next(!slideoutSource)
}

chat.component.ts (contains the trigger for a slide out)

export class ChatsComponent implements OnInit {

  constructor(private dataShare: DataShareService) { }

  toggleChat() {
    this.dataShare.toggleSlideout();
  }

  ngOnInit(): void {
  }

}

chat-window.component.ts (the component that holds the slide out)

export class ChatWindowComponent implements OnInit {
  open: boolean;
  private subscription: Subscription;
  chatTitle = 'Your Conversations';
  
  constructor(private dataShare: DataShareService) { }

  ngOnInit() {
    this.subscription = this.dataShare.slideoutStatus$.subscribe(value => this.open = value);
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

}

So, this seems to work as expected however I want to use the same service to open another unrelated slide out elsewhere in the app. I don't know how to go from what I have at the moment and make it reusable for multiple instances. Can anyone help?

CodePudding user response:

@Component({
  selector: 'chat-window',
  providers: [DataShareService]
})

This way the component has his own instance of the service.

CodePudding user response:

I believe better understanding of how the DI in Angular works, will be beneficial. Here is a complete guide about that, and I will just put a useful summary bellow about your problem:

When you create a service using Angular CLI it by default is provided in root module, and what that means is basically - you will have always a single instance of this class. So no matter how many components will inject that service, they will share the same instance.

In order to provide individual instance for each of the component you have to provide it for the component implicitly.

  1. Remove providedIn: 'root' in the service file
  2. Add service in providers array in each component's meta data:
@Component({
  selector:    'app-chat-window',
  templateUrl: './chat-window.component.html',
  providers:  [ DataShareService ]
})
  • Related