billy_56
billy_56

Reputation: 679

How come data is fetched with ActivatedRoute.snapshot.data['']?

I just started learning Angular, and I saw this piece of code:

export class ProductListComponent implements OnInit {

  private Products: Product[];


  constructor(private _activatedRoute: ActivatedRoute) 
  {
   
  }

  ngOnInit() {
    this.Products = this._activatedRoute.snapshot.data['Products'];
  }

}

And it's obvious someone is getting data using this code:

this._activatedRoute.snapshot.data['Products'];

How come services are not used to get data? And I'm wondering where this data are coming from then?

Upvotes: 0

Views: 3106

Answers (1)

Sravan
Sravan

Reputation: 18647

this._activatedRoute.snapshot.data['Products']; this code is not getting the data from the database and you got confused by that.

It is the data that you sent while navigationg through routes

During a navigation, after redirects have been applied, the router creates a RouterStateSnapshot

So what is a RouteStateSnapshot:

Official Definition:

Contains the information about a route associated with a component loaded in an outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router state tree.

Little more explanation:

RouteStateSnapshot is an immutable data structure representing the state of the router at a particular moment in time. Any time a component is added or removed or parameter is updated, a new snapshot is created.

Here is the actual code of that snapshot

interface RouterStateSnapshot {
  root: ActivatedRouteSnapshot;
}

interface ActivatedRouteSnapshot {
  url: UrlSegment[];
  params: {[name:string]:string};
  data: {[name:string]:any};

  queryParams: {[name:string]:string};
  fragment: string;

  root: ActivatedRouteSnapshot;
  parent: ActivatedRouteSnapshot;
  firstchild: ActivatedRouteSnapshot;
  children: ActivatedRouteSnapshot[];
}

It contains the details of URL, component, data, params etc

Let us look into an example and route configuration:

[
  {
    path: ':folder',
    children: [
      {
        path: '',
        component: ConversationsCmp
      },
      {
        path: ':id',
        component: ConversationCmp,
        children: [
          {
            path: 'messages',
            component: MessagesCmp
          },
          {
            path: 'messages/:id',
            component: MessageCmp,
            resolve: {
              message: MessageResolver
            }
          }
        ]
      }
    ]
  }
]

When we are navigating to /inbox/10/messages/11, the router will look at the URL and will construct the following RouterStateSnapshot:

component: MessageCmp
url: [‘messages’, ‘11’]
params: {id: ’10‘}
data: {}

So, the product data you are thinking may come from this route data

This is the refered documentation

Here is the documentation

Upvotes: 2

Related Questions