Answer the question
In order to leave comments, you need to log in
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();
}
Answer the question
In order to leave comments, you need to log in
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.
deleteShredderEvt = new Subject();
ngOnInit() {
this.deleteShredderEvt.pipe(
switchMap((shredderId) => this._shredService.deleteShredder(shredderId))
)
.subscribe();
}
<button (click)="deleteShredderEvt.next(shredderId)"></button>
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 questionAsk a Question
731 491 924 answers to any question