angular2-chapter05

Routing and Navigation

Check code at: https://github.com/wghglory/angular2-fundamental

Adding event-detail page

  1. shared/event.service.ts
export class EventService {
    getEvents() {
        return EVENTS
    }
    //add getEvent by id
    getEvent(id: number) {
        return EVENTS.find(e => e.id === id)
    }
}
  1. Access url parameter, create app/events/event-detail/event-detail.component.ts
//http://localhost:8808/events/3
import {Component, OnInit} from '@angular/core'
import {EventService} from '../shared/event.service'
import {ActivatedRoute} from '@angular/router'

@Component({
    templateUrl: '/app/events/event-detail/event-detail.component.html',
    styles: [`
        .container{padding:0 20px;}
        .event-img{height:100px;}
    `]
})
export class EventDetailComponent implements OnInit {
    constructor(private eventService: EventService, private route: ActivatedRoute) { }

    event: any

    ngOnInit() {
        //+ convert string to number
        this.event = this.eventService.getEvent(+this.route.snapshot.params['id'])
    }
}
  1. create its template:
<div class="container">
    <img [src]="event?.imageUrl" [alt]="event?.name" class="event-img">
    <div class="row">
        <div class="col-md-11">
            <h2>{{event?.name}} </h2>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <div><strong>Date:</strong> {{event?.date}}</div>
            <div><strong>Time:</strong> {{event?.time}}</div>
            <div><strong>Price:</strong> ${{event?.price}}</div>
        </div>
        <div class="col-md-6">
            <address>
                <strong>Address:</strong><br />
                {{event?.location?.address}}<br />
                {{event?.location?.city}}, {{event?.location?.country}}
            </address>
        </div>
    </div>
</div>
  1. register component in module
import { EventDetailComponent } from './events/event-detail/event-detail.component'

@NgModule({
    declarations: [AppComponent, EventsListComponent, EventThumbnailComponent, NavBarComponent, EventDetailComponent],
    providers: [EventService, ToastrService],
})
export class AppModule { }

Adding Routing

  1. Current app load component like below (app.component.ts). It has nav-bar and events-list components. Nav-bar should show all the time while events-list should show only when url is "/", so we should remove events-list and use router-outlet instead.

old app.component.ts:

@Component({
    selector: 'events-app',
    template: `<nav-bar></nav-bar><events-list></events-list>`
})

new app.component.ts using router:

@Component({
    selector: 'events-app',
    template: `<nav-bar></nav-bar><router-outlet></router-outlet>`
})
  1. create app/routes.ts
import {Routes} from '@angular/router'
import {EventsListComponent} from './events/events-list.component'
import {EventDetailComponent} from './events/event-detail/event-detail.component'

export const appRoutes: Routes = [
    { path: 'events', component: EventsListComponent },
    { path: 'events/:id', component: EventDetailComponent },
    { path: '', redirectTo: '/events', pathMatch: 'full' }  //pathMatch: prefix or full
]
  1. register routes array and Router module
import { RouterModule } from '@angular/router'
import { appRoutes } from './routes'

@NgModule({
    imports: [BrowserModule, RouterModule.forRoot(appRoutes)],
})
export class AppModule { }
  1. tell angular where app is hosted. Add base in index.html
<head>
    <base href="/">
</head>

Linking to Routes

events-list any thumbnail click => specific events/id page
nav-bar "allEvents" click => load all events: localhost/

event-thumbnail.component.ts: [routerLink]="['/events', event.id]"

<div [routerLink]="['/events', event.id]" class="well hoverwell thumbnail">
    <h2>Event: {{event?.name}}</h2>
    <div>Price: \${{event?.price}}</div>
    <div>Date: {{event?.date}}</div>
</div>

nav.component.html:

<li><a [routerLink]="['/events']">All Events</a></li>

Navigating from Code

  1. create events/create-event.component.ts
//click cancel will use router to navigate to /events (load all events)
import {Component} from '@angular/core'
import {Router} from '@angular/router'

@Component({
    template: `
    <h1>New Event</h1>
    <div class="col-md-6">
        <h3>[Create Event Form will go here]</h3>
        <button type="submit" class="btn btn-primary">Save</button>
        <button type="button" class="btn btn-default" (click)="cancel()">Cancel</button>
    </div>
    `
})
export class CreateEventComponent {
    constructor(private router:Router){}

    cancel(){
        this.router.navigate(['/events'])
    }
}
  1. update routes.ts with CreateEventComponent and route events/new:
import {Routes} from '@angular/router'
import {EventsListComponent} from './events/events-list.component'
import {EventDetailComponent} from './events/event-detail/event-detail.component'
import {CreateEventComponent} from './events/create-event.component'

export const appRoutes: Routes = [
    { path: 'events/new', component: CreateEventComponent }, //order matters
    { path: 'events', component: EventsListComponent },
    { path: 'events/:id', component: EventDetailComponent },
    { path: '', redirectTo: '/events', pathMatch: 'full' }  //pathMatch: prefix or full
]
  1. nav/nav.component.html
<ul class="nav navbar-nav">
    <li><a [routerLink]="['/events']">All Events</a></li>
    <li><a [routerLink]="['/events/new']">Create Event</a></li>
</ul>
  1. register component in module:
import { CreateEventComponent} from './events/create-event.component'
import { RouterModule } from '@angular/router'
import { appRoutes } from './routes'

@NgModule({
    imports: [BrowserModule, RouterModule.forRoot(appRoutes)],
    declarations: [AppComponent, EventsListComponent, EventThumbnailComponent, NavBarComponent, EventDetailComponent, CreateEventComponent],
})
export class AppModule { }

Guarding Against Route Activation (Invalid event id like 1000 which doesn't exist, navigate to 404)

  1. create errors/404.component.ts, register module, register router
import { Component } from '@angular/core'

@Component({
    template: `
        <h1 class="errorMessage">404'd</h1>
      `,
    styles: [`
        .errorMessage {
             margin-top:150px;
             font-size: 170px;
             text-align: center;
        }`]
})
export class Error404Component {
    constructor() {

    }

}
  1. create events/event-detail/event-route-activator.service.ts and register this EventRouteActivator service into app.module.ts providers
import { Router, ActivatedRouteSnapshot, CanActivate } from '@angular/router'
import { Injectable } from '@angular/core'
import { EventService} from '../shared/event.service'

@Injectable()
export class EventRouteActivator implements CanActivate {
    constructor(private eventService: EventService, private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot) {
        const eventExists = !!this.eventService.getEvent(+route.params['id'])  //+ convert

        if (!eventExists)
            this.router.navigate(['/404'])

        return eventExists
    }
}

app.component.ts

import { Error404Component } from './errors/404.component'
import { EventRouteActivator } from './events/event-detail/event-route-activator.service'
import { RouterModule } from '@angular/router'
import { appRoutes } from './routes'

@NgModule({
    imports: [BrowserModule, RouterModule.forRoot(appRoutes)],
    declarations: [
        AppComponent,
        NavBarComponent,
        EventsListComponent, EventThumbnailComponent, EventDetailComponent, CreateEventComponent,
        Error404Component
    ],
+    providers: [EventService, ToastrService, EventRouteActivator],
    bootstrap: [AppComponent]
})
export class AppModule { }
  1. routes.ts add canActivate and EventRouteActivator service

note: route canActivate can use both service and function. Here we're using service

import {Routes} from '@angular/router'
import {EventsListComponent} from './events/events-list.component'
import {EventDetailComponent} from './events/event-detail/event-detail.component'
import {CreateEventComponent} from './events/create-event.component'

import {Error404Component} from './errors/404.component'

+ import {EventRouteActivator} from './events/event-detail/event-route-activator.service'

export const appRoutes: Routes = [
    { path: 'events/new', component: CreateEventComponent }, //order matters
    { path: 'events', component: EventsListComponent },
+    { path: 'events/:id', component: EventDetailComponent, canActivate: [EventRouteActivator] },
    { path: '404', component: Error404Component },
    { path: '', redirectTo: '/events', pathMatch: 'full' }  //pathMatch: prefix or full
]

Guarding Against Route De-activation (User navigates to other url before saving data, like cancel button clicking)

  1. routes.ts add canDeactivate, and we're using function.
import {Routes} from '@angular/router'
import {EventsListComponent} from './events/events-list.component'
import {EventDetailComponent} from './events/event-detail/event-detail.component'
import {CreateEventComponent} from './events/create-event.component'

import {Error404Component} from './errors/404.component'

import {EventRouteActivator} from './events/event-detail/event-route-activator.service'

export const appRoutes: Routes = [
+    { path: 'events/new', component: CreateEventComponent, canDeactivate: ['canDeactivateCreateEvent'] },
    { path: 'events', component: EventsListComponent },
    { path: 'events/:id', component: EventDetailComponent, canActivate: [EventRouteActivator] },
    { path: '404', component: Error404Component },
    { path: '', redirectTo: '/events', pathMatch: 'full' }  //pathMatch: prefix or full
]

We defined canDeactivateCreateEvent function, and we should register this in module's providers. Now our providers are like providers: [EventService, ToastrService, EventRouteActivator]. Actually we already used the shorthand way for providers. Take EventService for instance, the longhand is providers: [{provide:EventService, useValue:EventService}]. So below is how we register the canDeactivateCreateEvent function into the providers.

app.module.ts:

@NgModule({
    imports: [BrowserModule, RouterModule.forRoot(appRoutes)],
    declarations: [
        AppComponent,
        NavBarComponent,
        EventsListComponent, EventThumbnailComponent, EventDetailComponent, CreateEventComponent,
        Error404Component
    ],
    providers: [
        EventService,
        ToastrService,
        EventRouteActivator,
+        {
+            provide: 'canDeactivateCreateEvent',
+            useValue: checkDirtyState
+        }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

//this function can be defined in another file
+function checkDirtyState(component: CreateEventComponent) {
+    if(component.isDirty){
+        return confirm('you haven\'t save the event. Are you sure to cancel?')
+    }
+    return true;
+}
  1. create-event.component.ts add isDirty
//click cancel will use router to navigate to /events (load all events)
import {Component} from '@angular/core'
import {Router} from '@angular/router'

@Component({})
export class CreateEventComponent {
+    isDirty: boolean = true

    constructor(private router: Router) { }

    cancel() {
        this.router.navigate(['/events'])
    }
}

Pre-loading Data for Components

In real world, we may have some delay to receive data from ajax call. To show this issue,

  1. simulate ajax loading data in event.service.ts, so it takes 2 second to get data
+ import { Subject } from 'rxjs/RX'

@Injectable()
export class EventService {
    getEvents() {
        //simulate async loading data operation, return subject. Need to change events-list.component.ts
+        let subject = new Subject()
+        setTimeout(() => {
+            subject.next(EVENTS);
+            subject.complete();
+        }, 2000)

+        return subject;
    }
}
  1. in events-list.component.ts
export class EventsListComponent implements OnInit {
+    events: any   //before was events: any[], now compiler won't complain

    ngOnInit() {
-        // this.events = this.eventService.getEvents()
+        this.eventService.getEvents().subscribe(events => { this.events = events })
    }
}

Now when we navigate to base page, we can immediately see <h1>Upcoming Angular 2 Events</h1>, but it takes 2 second before showing data. Similar issue is like table header shows immediately but data is still loading. So we will use a resolver to make sure the template html along with data will be loaded once at the same time

  1. create events-list-resolver.service.ts and then register provider in module
import {Injectable} from '@angular/core'
import {Resolve} from '@angular/router'
import {EventService} from './shared/event.service'

@Injectable()
export class EventListResolver implements Resolve<any>{
    constructor(private eventService: EventService) {

    }

    resolve() {
        // map() return Observable; subscribe() return subscription
        // in resolve, we need to return Observable. angular can watch Observable and see if it finishes
        return this.eventService.getEvents().map(events => events);
    }
}
  1. use resolver in the routes by resolve: { events:1 EventListResolver }. events1 is property that will be passed to component after calling Resolver.
+ import {EventListResolver} from './events/events-list-resolver.service'

export const appRoutes: Routes = [
    //order matters
    { path: 'events/new', component: CreateEventComponent, canDeactivate: ['canDeactivateCreateEvent'] }, //Guarding Against Route De-activation using function, canDeactivateCreateEvent is provider name which points to a function
+    { path: 'events', component: EventsListComponent, resolve: { events1: EventListResolver } }, //call EventListResolver before using the component, bind resolver result to a property events1, and this property will be passed to the component
    { path: 'events/:id', component: EventDetailComponent, canActivate: [EventRouteActivator] }, //Guarding Against Route Activation using service
    { path: '404', component: Error404Component },
    { path: '', redirectTo: '/events', pathMatch: 'full' }  //pathMatch: prefix or full
]
  1. consume the events property in events-list.component
import {ActivatedRoute} from '@angular/router'

export class EventsListComponent implements OnInit {
    events: any[]

    constructor(private eventService: EventService, private toastrService: ToastrService, private route: ActivatedRoute) {
    }

    ngOnInit() {
        // // this.events = this.eventService.getEvents()
        // this.eventService.getEvents().subscribe(events => { this.events = events })  //since we are using resolver
        this.events = this.route.snapshot.data['events1'];
    }
}

Styling Active Links

  1. define active class in nav.component.ts
import {Component} from '@angular/core'

@Component({
    selector: 'nav-bar',
    templateUrl: 'app/nav/nav.component.html',
    styles: [`
        .nav.navbar-nav {font-size:15px;}
        #searchForm {margin-right:100px;}
        @media(max-width:1200px) {#searchForm {display:none;}}
+        li>a.active{color:#f97924;}
    `]
})
export class NavBarComponent { }
  1. in nav.component.html add routerLinkActive="active"

When navigating to events/new, both will have active class by default. This is because routerLinkActive finds both start with /events. So we also add [routerLinkActiveOptions]="{exact:true}"

<li><a [routerLink]="['/events']" routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">All Events</a></li>
<li><a [routerLink]="['/events/new']" routerLinkActive="active">Create Event</a></li>

Lazily Loading Feature Modules

For now we only have 1 module.

let's create a user profile and since user is different part of our app, we want to use another lazily loading feature module. This module will be loaded only when user navigates to the module, so it affects the performance for a larger application.

  1. user/user.module.ts
import { NgModule } from '@angular/core'
import { RouterModule } from '@angular/router'
import { CommonModule } from '@angular/common'
import {userRoutes} from './user.routes'
import {ProfileComponent} from './profile.component'

@NgModule({
    imports: [
        CommonModule,
        RouterModule.forChild(userRoutes)
    ],
    declarations: [
        ProfileComponent
    ],
    providers: [

    ],
    bootstrap: []
})
export class UserModule { }
  1. user/profile.component.ts
import { Component } from '@angular/core'

@Component({
  template: `
    <h1>Edit Your Profile</h1>
    <hr>
    <div class="col-md-6">
      <h3>[Edit profile form will go here]</h3>
      <br />
      <br />
      <button type="submit" class="btn btn-primary">Save</button>
      <button type="button" class="btn btn-default">Cancel</button>
    </div>
  `,
})
export class ProfileComponent {}
  1. user/user.routes.ts
import {ProfileComponent} from './profile.component'

export const userRoutes = [
    { path: 'profile', component: ProfileComponent }
]
  1. In routes.ts:
export const appRoutes: Routes = [
    ...
    // user prefix, localhost/user/x, will load module here: app/user/user.module and the module name is UserModule, concat '#'
    { path: 'user', loadChildren: 'app/user/user.module#UserModule' }
]
  1. in nav/nav.component.html
<li><a [routerLink]="['user/profile']">Welcome Guanghui</a></li>

Organizing Your Exports with Barrels

Now our app.component.ts has too many import, we can use Barrels to simplify the Event import

  1. create index.ts under events folder and its subfolder. In this case, there should be 3 index.ts

events/index.ts

export * from './create-event.component'
export * from './event-thumbnail.component'
export * from './events-list-resolver.service'
export * from './events-list.component'
export * from './shared/index'
export * from './event-detail/index'

events/shared/index.ts

export * from './event.service'

events/event-detail/index.ts

export * from './event-detail.component'
export * from './event-route-activator.service'
  1. delete all event related import, and use below:
import {
    EventsListComponent,
    EventThumbnailComponent,
    EventDetailComponent,
    CreateEventComponent,
    EventRouteActivator,
    EventService,
    EventListResolver
} from './events/index'
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子稚失,更是在濱河造成了極大的恐慌原朝,老刑警劉巖悯森,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吧兔,死亡現(xiàn)場(chǎng)離奇詭異状植,居然都是意外死亡钓瞭,警方通過(guò)查閱死者的電腦和手機(jī)驳遵,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)山涡,“玉大人堤结,你說(shuō)我怎么就攤上這事⊙即裕” “怎么了竞穷?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)鳞溉。 經(jīng)常有香客問(wèn)我瘾带,道長(zhǎng),這世上最難降的妖魔是什么熟菲? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任看政,我火速辦了婚禮朴恳,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘允蚣。我一直安慰自己于颖,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布嚷兔。 她就那樣靜靜地躺著森渐,像睡著了一般。 火紅的嫁衣襯著肌膚如雪冒晰。 梳的紋絲不亂的頭發(fā)上章母,一...
    開(kāi)封第一講書(shū)人閱讀 51,631評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音翩剪,去河邊找鬼乳怎。 笑死,一個(gè)胖子當(dāng)著我的面吹牛前弯,可吹牛的內(nèi)容都是我干的蚪缀。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼恕出,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼询枚!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起浙巫,我...
    開(kāi)封第一講書(shū)人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤金蜀,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后的畴,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體渊抄,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年丧裁,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了护桦。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡煎娇,死狀恐怖二庵,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情缓呛,我是刑警寧澤催享,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站哟绊,受9級(jí)特大地震影響因妙,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一兰迫、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧炬称,春花似錦汁果、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至跷车,卻和暖如春棘利,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背朽缴。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工善玫, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人密强。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓茅郎,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親或渤。 傳聞我的和親對(duì)象是個(gè)殘疾皇子系冗,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • collections常見(jiàn)的方法
    白敏鳶閱讀 1,126評(píng)論 0 0
  • 史料記載,孔子身高1.9米薪鹦,而齊國(guó)大夫晏嬰身高只有1.3米掌敬,兩個(gè)身高相差巨大的春秋政治家,在夾谷會(huì)盟中結(jié)下了梁子池磁,...
    任艾軍閱讀 528評(píng)論 1 0
  • 我司新版本有優(yōu)惠券的功能奔害,且趕上要上重大活動(dòng),所以此版本如期重中之重地熄。因?yàn)橐恍﹫F(tuán)隊(duì)原因和個(gè)人原因延期提審舀武。4月9號(hào)...
    獵戶座防線閱讀 2,551評(píng)論 4 6