Reputation: 155
I've read some articles about Observable and unsubscribes. But I don't understand a bit of information about the pipe(). Pipe automatically unsubscribes in some cases. What are these cases? I have one service for connecting to my server and one component. Should I unsubscribe here and using ngOnDestroy? It simple service for CRUD application.
For example, one method from service:
public getSubject(size:number, page:number) : Observable<Subject[]> {
return this.http.get<Subject[]>(environment.apiUrl + '/subject?size='+size+'&page='+page)
.pipe(
map(data=>{
return data;
}),
catchError(err => {
return throwError(err);
}));
}
And component using the service with destroyer.
//...some code
pageClick() {
this.subscriptions.add(this.connector.getSubject(this.pageSize, this.page - 1)
.subscribe(data => {
this.subject = data;
this.errorFlag = false;
}, error => {
this.error = error.error.message;
this.errorFlag = true;
}));
}
//..some code..
@HostListener('window:beforeunload')
ngOnDestroy() {
this.subscriptions.unsubscribe();
}
Upvotes: 1
Views: 2663
Reputation: 1132
There is no need to unsubscribe completed Observable. When HttpClient gets response from server and emits it to subscription in component Observable is completed, so it emits no more values. If it's not emitting values, there is no risk of memory leak, which is reason unsubscribing.
"Pipe automatically unsubscribes in some cases" - .pipe is used to modify stream of data by adding some operators to it. It is not responsible for subscribing nor unsubscribing.
Upvotes: 7