viktor-shmigol / ng2-cable

Connect your Angular(2/4)/ionic(2/3) application with Rails ActionCable
https://ng2-cable-example.herokuapp.com
44 stars 14 forks source link

How do I unsubscribe from a specific channel? #17

Closed NuclearMachine closed 6 years ago

viktor-shmigol commented 6 years ago

@NuclearMachine, Thanks for question. You can try something like this:

let subscription = this.broadcaster.on('newMessage').subscribe((message) => {
  //some code
})
subscription.unsubscribe();

or

export class Messages implements OnInit {
  private subscriptions:any = [];

  constructor(private broadcaster: Broadcaster) {}

  ngOnInit() {
    this.initListeners();
  }

  ngOnDestroy() {
    this.unsubscribe();
  }

  initListeners() {
    this.subscriptions = this.subscriptions.concat([
      this.broadcaster.on('newMessage').subscribe(this.newMessageHandler),
      this.broadcaster.on('newUserRequest').subscribe(this.newUserRequestHandler)
    ])
  }

  newMessageHandler = (data) => {
    //some code
  }

  newUserRequestHandler = (data) => {
    //some code
  }

  unsubscribe() {
    this.subscriptions.forEach((subscription) => subscription.unsubscribe());
  }
}
this.ng2cable.subscribe('http://example.com/cable', 'ChatChannel', { room: 'My room' });
this.ng2cable.unsubscribe();