Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

angular - What is the difference between ActivatedRoute and ActivatedRouteSnapshot in Angular4

What is the difference between ActivatedRouteSnapshot and ActivatedRoute in Angular 4? It's my understanding that ActivatedRouteSnapshot is a child of ActivatedRoute, meaning that ActivatedRoute contains ActivatedRouteSnapshot.

Incidentally, I tried running a Google search for an answer to this question, but I didn't find any of the search results to be understandable.

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since ActivatedRoute can be reused, ActivatedRouteSnapshot is an immutable object representing a particular version of ActivatedRoute. It exposes all the same properties as ActivatedRoute as plain values, while ActivatedRoute exposes them as observables.

Here is the comment in the implementation:

export class ActivatedRoute {
  /** The current snapshot of this route */
  snapshot: ActivatedRouteSnapshot;

If a router reuses a component and doesn't create a new activated route, you will have two versions of ActivatedRouteSnapshot for the same ActivatedRoute. Suppose you have the following routing configuration:

path: /segment1/:id,
component: AComponent

Now you navigate to:

/segment1/1

You will have the param in the activatedRoute.snapshot.params.id as 1.

Now you navigate to:

/segment1/2

You will have the param in the activatedRoute.snapshot.params.id as 2.

You can see it by implementing the following:

export class AComponent {
  constructor(r: ActivatedRoute) {    
    r.url.subscribe((u) => {
      console.log(r.snapshot.params.id);
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...