首页 > 技术文章 > Routing in Angular 2 RC.1

ztguang 2016-06-08 16:02 原文


https://playcode.org/routing-in-angular-2-rc-1/


The Angular Component Router enables navigation from one view to the next as users perform application tasks.

What I am going to show in this article is how to create a simple navigation in Angular 2 with Typescript and the Router component.

Is Angular 2 Ready?

Angular 2 is in Release Candidate Stage. Recently there where announcements that made clear that the Angular 2 final release is just around the corner. Angular 2 Release Candidate

Requirements

If you already have Node.js installed, install the Angular command line tools with npm:

npm install -g angular-cli

Getting Started

1. Create a new project
ng new <project-name>
cd <project-name>
2. Create new routes
ng generate route login
ng generate route dashboard

By default the route will be designated as a lazy route which means that it will be loaded into the browser when needed.

The default lazy nature of routes can be turned off via the lazy flag (--lazy false). More about lazy routes in Routing - ng-conf video.

This will be your main app component with the new routes generated:

    import { Component } from '@angular/core';
    import { Routes, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from '@angular/router';

    import { LoginComponent } from './+login';
    import { DashboardComponent } from './+dashboard';

    @Component({
      moduleId: module.id,
      selector: 'routing-example-app',
      templateUrl: 'routing-example.component.html',
      styleUrls: ['routing-example.component.css'],
      directives: [ROUTER_DIRECTIVES],
      providers: [ROUTER_PROVIDERS]
    })
    @Routes([
      {path: '/dashboard', component: DashboardComponent},
      {path: '/login', component: LoginComponent}
    ])
    export class RoutingExampleAppComponent {
      title = 'routing-example works!';
    }
3. Routing

Let's modify our components to simulate a login process and navigate to the dashboard view.

main.component.ts

    import { Component } from '@angular/core';
    import { Routes, Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from '@angular/router';

    import { LoginComponent } from './+login';
    import { DashboardComponent } from './+dashboard';

    @Component({
      moduleId: module.id,
      selector: 'routing-example-app',
      templateUrl: 'routing-example.component.html',
      styleUrls: ['routing-example.component.css'],
      directives: [ROUTER_DIRECTIVES],
      providers: [ROUTER_PROVIDERS]
    })
    @Routes([
      {path: '/dashboard', component: DashboardComponent},
      {path: '/login', component: LoginComponent},
      {path: '*', component: LoginComponent}
    ])
    export class RoutingExampleAppComponent {

        title = 'routing-example works!';

        constructor(private router: Router) {}

        ngOnInit() {
            let auth:string = localStorage.getItem('auth');
            if (auth === 'logged') {
                console.log("Logged");
                this.router.navigate(['/dashboard']);
            }else{
                console.log("Not Logged");
                this.router.navigate(['/login']);
            }
        }
    }

login.component.ts

    import { Component, OnInit } from '@angular/core';

    @Component({
      moduleId: module.id,
      selector: 'app-login',
      templateUrl: 'login.component.html',
      styleUrls: ['login.component.css']
    })
    export class LoginComponent implements OnInit {

        constructor() {}

        ngOnInit() {}

        login(){
            console.log("Login...");
            localStorage.setItem('auth', 'logged');
        }
    }

login.component.html

    <a href="#" (click)="login();">Login</a>

Run the serve command and go to localhost:4200 in your browser:

ng serve

Routing and Navigation in Angular 2 RC.1 - LoginRouting and Navigation in Angular 2 RC.1 - Dashboard

4. Partials and subroutes

Now that we have our example working and simulating a login process, let's create a layout with "partials and subroutes" to our dashboard.

ng generate component topbar
ng generate route home
ng generate route help
ng generate route about

Routing and Navigation in Angular 2 RC.1 - Topbar

5. Move all new routes to the dashboard

It's time to move all new subroutes to our dashboard component, add the topbar to the dashboard and add all new links to each subroute in our topbar:

dashboard.component.html

    <p>
      dashboard works!
    </p>

    <app-topbar></app-topbar>

    <router-outlet></router-outlet>

dashboard.component.ts

import { Component, OnInit } from '@angular/core';
import { Routes, ROUTER_DIRECTIVES} from '@angular/router';

import { TopbarComponent } from '../topbar';

import { HomeComponent } from '../+home';
import { HelpComponent } from '../+help';
import { AboutComponent } from '../+about';

@Component({
  moduleId: module.id,
  selector: 'app-dashboard',
  templateUrl: 'dashboard.component.html',
  styleUrls: ['dashboard.component.css'],
  directives: [ROUTER_DIRECTIVES, TopbarComponent]
})
@Routes([
  {path: '', component: HomeComponent},
  {path: '/home', component: HomeComponent},
  {path: '/help', component: HelpComponent},
  {path: '/about', component: AboutComponent}
])
export class DashboardComponent implements OnInit {

  constructor() {}

  ngOnInit() {
  }

}

topbar.component.html

<p>
  topbar works!
</p>

<a [routerLink]="[ '/dashboard/home' ]">Home</a>

<a [routerLink]="[ '/dashboard/help' ]">Help</a>

<a [routerLink]="[ '/dashboard/about' ]">About</a>

topbar.component.ts

import { Component, OnInit } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'app-topbar',
  templateUrl: 'topbar.component.html',
  styleUrls: ['topbar.component.css'],
  directives: [ROUTER_DIRECTIVES]
})
export class TopbarComponent implements OnInit {

  constructor() {}

  ngOnInit() {
  }

}
6. Serve

You are ready to go! Run the serve command and go to localhost:4200 in your browser:

ng serve

Voilà!

Routing and Navigation in Angular 2 RC.1 - HomeRouting and Navigation in Angular 2 RC.1 - HelpRouting and Navigation in Angular 2 RC.1 - About

Demo Code

Code Sample in Github

References

Angular-CLI

Angular 2 - 5 Min Quickstart

Routing & Navigation

Angular 2 Routing

Use the Angular CLI For Faster Angular 2 Projects

Keep up with my guides and how-tos like this by liking my Facebook Page. If you have any questions about working with Angular 2, please join the discussion below!



推荐阅读