A
A
alexbog902020-10-08 11:22:27
Angular
alexbog90, 2020-10-08 11:22:27

How to transfer the subscription to the stream from the method called by the user to ngOnInit()?

I heard the opinion that it's bad practice to subscribe to a stream inside a method that is called, say, by clicking on a button.

public deleteShredder(shredderId: string): void {
  this._shredService.deleteShredder(shredderId).pipe(
    switchMap(() => this._shredService.refreshShredderList()),
  ).subscribe();
}


For example, in this case, of course, I will unsubscribe from the subscription in onDestroy(), but how to make the code cleaner so that .subscribe() is in OnInit()?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shvets, 2020-10-08
@alexbog90


I heard the opinion that it's bad practice to subscribe to a stream inside a method that is called, say, by clicking on a button.

The first time I've heard.
But if you like.
deleteShredderEvt = new Subject();

ngOnInit() {
  this.deleteShredderEvt.pipe(
    switchMap((shredderId) => this._shredService.deleteShredder(shredderId))
  )
    .subscribe();
}

<button (click)="deleteShredderEvt.next(shredderId)"></button>

what a thread is. Instead of subscribing, you can initiate an event, and in on-in subscribe to a chain starting from this event

D
Demian Smith, 2020-10-08
@search

Try to reduce your work with observables to subscribing to them via asyncPipe. In this case, Angular will manage subscriptions/unsubscriptions for you.
I won’t tell you how to do it correctly, because I myself came to this too late by the end of a two-year project and have not encountered Angular for a year and a half. But it looks like it's possible. IMHO, you need to keep your head on your shoulders and not try to get out with RxJS at all costs, because in a month it will not be clear how it works.
A good rule of thumb with RxJS is to try to defer the call to subscribe until later. The code will be more flexible if your methods do not call subsctibe but return observable. And the subscription to the observable itself takes place somewhere else (for example, in the same asyncPipe). Well, or in the place where there is simply no way without a subscription :-) Many novice anglers are afraid of RxJS like fire and subscribe to observables as soon as possible, and then manage the code in the usual inactive form. This style of coding usually ends up complaining about the framework itself (they say it can't do anything).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question