What is the difference between ActivatedRoute and ActivatedRouteSnapshot in Angular4

前端 未结 3 1382
有刺的猬
有刺的猬 2020-12-02 08:44

What is the difference between ActivatedRouteSnapshot and ActivatedRoute in Angular 4? It\'s my understanding that ActivatedRouteSnapshot

3条回答
  •  一个人的身影
    2020-12-02 09:12

    There are 2 ways to get the parameter from the route.

    1. Snapshot (route.snapshot.paramMap.get). Read it during init.

    Use the Snapshot if you only need the initial value of the parameter once during the component's initialization, and don't expect the URL to change while the user is still on that same component.

    • I.e. if on a product/2 route, and the only way they'd get to product/3 is by going back to the product search screen and then clicking a product detail (leaving the detail component, then re-opening it with a new route param)

    2. Observable (route.paramMap.subscribe). Subscribe to it during init.

    Use the Observable if it's possible for the route to change while the user is still on the same component, and hence the Component's initialization would not be called again, but the observable would call your subscribed logic when the URL changed.

    • I.e. if on a product/2 route, and you have a "next" button to go to the next id record product/3, hence the user did not leave/re-open the component but the URL did receive a new param.

    Generally speaking, subscribing is the safest route if you're unsure.

提交回复
热议问题