I have a couple of questions about Angular. I recently started to experiment with Angular and really cant get a grip of when I should unsubscribe, there is obviously recommended to use the AsyncPipe but in some cases there is no way to use it.
If I subscribe to a HTTP request in a service, does the Observable unsubscribe itself or is it persistent through out the application lifetime?
When I subscribe (without the AsyncPipe) to a HTTP request in a component I could manually unsubscribe in the ngOnDestroy lifecycle hook which is fine but in my case I have a submit method to create account
account.component.html
<account-item> *ngFor="let account of collection$" [data]="account" </account-item>
account.component.ts
public collection$: Observable<Account[]>; private subscription: Subscription; constructor( private service: AccountService ) {} ngOnInit() { this.collection$ = this.service.getAll() } createAccount(obj) { this.subscription = this.service.create(obj) .subscribe( success => this.collection$ = this.service.getAll(), error => Observable.throw(error) ); } ngOnDestroy() { this.subscription.unsubscribe(); }
From what I know the subscription is now persistent until my AccountComponent is destroyed, but is there a way to use AsyncPipe here instead or is it better for me to subscribe in the service itself?
I've read something about finite and infinite Observables but haven't really understand when a Observable is finite or not.
- Another problem I'm facing is that in
success => this.collection$ = this.service.getAll()
my UI doesn't update with the new account list when I useChangeDetectionStrategy.OnPush
but works just fine withChangeDetectionStrategy.Default
This is the service method that fetches the account data
getAll() { return this.http.get(ENDPOINT_ACCOUNT) .map((response: Response) => response.json().data) }