docs: clarify expectations for `ActivatedRoute` observables (#42316)

https://github.com/angular/angular/issues/16261#issuecomment-748289240

A couple important things to note about the behavior:

* The component is destroyed, meaning that all of its members will be destroyed as well, including any subscriptions to the route params
* This _does not_ mean that any `finalize` operators or `complete` on the subscription is called. This only happens if the source completes or you unsubscribe from the subscription. The documentation doesn't state that the `Router` will do this, though I can still understand why the behavior is confusing.

You can play around with these scenarios here:
https://stackblitz.com/edit/rxjs-hmpizx
* `complete` the source without unsubscribe: `next`, `complete` and `finalize` are all called, even when `complete` is called before the `next` from the `delay`
* `unsubscribe` from subscription without `complete` on the source: `finalize` happens, but the `complete` of the subscription does not, and neither does `next`

So even if the `Router` were to call `complete` on all of the `Observables` on an `ActivatedRoute`, you would see that any subscriptions with a `delay` operator would still get called.

resolves #16261

PR Close #42316
This commit is contained in:
Andrew Scott 2021-05-25 08:50:02 -07:00 committed by Zach Arend
parent 9f09c3b9b1
commit 29e5d509aa
1 changed files with 6 additions and 1 deletions

View File

@ -1002,7 +1002,12 @@ Since `ngOnInit()` is only called once per component instantiation, you can dete
When subscribing to an observable in a component, you almost always unsubscribe when the component is destroyed.
However, `ActivatedRoute` observables are among the exceptions because `ActivatedRoute` and its observables are insulated from the `Router` itself.
The `Router` destroys a routed component when it is no longer needed along with the injected `ActivatedRoute`.
The `Router` destroys a routed component when it is no longer needed. This means all the component's members will also be destroyed,
including the injected `ActivatedRoute` and the subscriptions to its `Observable` properties.
The `Router` does not `complete` any `Observable` of the `ActivatedRoute` so any `finalize` or `complete` blocks will not run.
If you need to handle something in a `finalize`, you will still need to unsubscribe in `ngOnDestroy`. You will also have to
unsubscribe if your observable pipe has a delay with code you do not want to run after the component is destroyed.
</div>