angular2 step by step #3 - hello world routing

routing is critical for every web framework architecture.  ASP.net / JSP have server side routing built-in, dealing with http modules and handler. Angular changes from server side architecture to client side, with the routing as well. Angular2 did it one step further

official Angular2 Routing here: https://angular.io/docs/ts/latest/guide/router.html. following is quick view on how routing works in angular2.

1. setup base for the client side app.
client visit "index.html" and load it into browser,  all the subsequent request routing is based on this root. treat this as a starting baseline for the client app.

    src/index.html (base-href) => <head> => <base href="/"> 

2. create new component.

    ng g component home

3. import routing module into application & configure routing

    app.module.ts =>  import { RouterModuleRouterfrom '@angular/router';

  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot([
      {path:'home'component:HomeComponent}
    ])
  ],

4. add a link some where to point to the "home", where to add the link? "app.componnet.html", why?

app.componnet.html is bootstrapped by app.module, and that's the page the user see first.  Navigations starts from here. add a "\home".

<a routerLink='/home'>home</a>

 

5. app.component.html will not refresh itself from server again when hitting '/home', instead it will check the routing, and try to load "homeComponent" from memory.

home component itself will load "home.componnet.html" NOT from server, but from memory. The content of "home.component.html" has already been serialized in the JS loaded. 

once home componnet view is rendered out, we need to have a place to put the content. hence, add a "router-outlet" as a place holder in the root "app.component.html"

<router-outlet></router-outlet>

 

 

<<official doc mentioned: "If the app folder is the application root", question, "what if the app folder is not the application root?">>

 eg. website is under "webroot/SampleApp/", when we hit index.html,

it will be "http://server1/SampleApp/index.html",
the routing urls will be pointing to "http://server1/SampleApp/home",
so we need to change <base href="/SampleApp"> to make the routing consistent. <-- this is a thought, not tested yet -->

 

posted @ 2017-03-28 18:57  chen.s  阅读(144)  评论(0编辑  收藏  举报