Tuesday 8 January 2019

Angular 6 Routing

When we run an Angular application and serve it on a port number say ( 4200 ), we get our application running at http://localhost:4200

This is the only path our browser understands, and hence it can’t serve different destinations on different paths such as http://localhost:4200/items. But, What if we have multiple paths in the same application ?

How to achieve custom URL paths

Javascript Router: It makes our lives easier by changing the destination whenever the path changes. In technical terms, by changing the application state whenever the browser URL changes and vice-versa.

These Routers are written in certain Javascript Frameworks and for Angular we have it packaged as @angular/router


The @angular/router contains the shown terms:


  1. Service: This is a global service present inside the Angular Application.
  2. State: The state of Router is maintained by Router State.
  3. Configuration: It maintains information about all the routing states which is present inside the application.
  4. Guard: This is a code that runs whenever the router is activated, deactivated or loaded.
  5. Snapshot: It will provide access to state and data for a particular route node.
  6. Resolver: The script that will fetch data before the requested page is initiated.
  7. Outlet: This is the location in DOM for router outlet to place it’s components.

Now Let's Code:

To tell the paths and destinations to your browser, you need to import the RouterModule and Routes from @angular/router into your app.module.ts file.
 
 
 
iTechnoFreaks
> import {RouterModule, Routes} from '@angular/router';
After this, you can define an array of your paths and destination pages.
 
 
 
iTechnoFreaks
const routes: Routes = [
  {
    path: '',
    redirectTo: 'items',
    pathMatch: 'full'
  },
  {
    path: 'items',
    component: AppComponent
  }
];
Note: Here, the pathMatch is specifying a strict matching of path to reach the destination page.
Now, you need to pass the routes array in the RouterModule using RouterModule.forRoot(routes) and have to add it to imports

 
 
 
iTechnoFreaks
> RouterModule.forRoot(routes)
app.module.ts file will look like this:
 
 
 
iTechnoFreaks
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import { AppComponent } from './app.component';


const routes: Routes = [
  {
    path: '',
    redirectTo: 'items',
    pathMatch: 'full'
  },
  {
    path: 'items',
    component: AppComponent
  }
];

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }