zoukankan      html  css  js  c++  java
  • [Angular 2] ROUTING IN ANGULAR 2 REVISITED

    Let's say we have a list of contacts, click each contact, we can render a new route to get the detail.

    Define the routers:

    //contact-list.router.ts
    
    import {ContactListComponent} from "./contact-list-component.component";
    import {ContactDetailComponent} from "./contact-detail-component/contact-detail-component.component";
    export const ContactsAppRoutes = [
      { path: '', component: ContactListComponent },
      { path: 'contacts/:id', component: ContactDetailComponent }
    ];

    path: '', --> here empty path means use this component by default.

    Bootstrap the router

    To use router, we need to provider the router service. 

    bootstrap(AppComponent, [
      provideRouter(ROUTER-OBJECT)
    ]); 
    import { bootstrap } from '@angular/platform-browser-dynamic';
    import { enableProdMode } from '@angular/core';
    import { AppComponent, environment } from './app/';
    import {ContactsAppRoutes} from './app/contact-list-component/contact-list.routes';
    import {provideRouter} from "@angular/router";
    
    if (environment.production) {
      enableProdMode();
    }
    
    bootstrap(AppComponent, [
      provideRouter(ContactsAppRoutes)
    ]);

    Create outlet for rendering the router:

    //app.component.html
    
    <h1>
      {{title}} Hello Router 3.0
    </h1>
    <router-outlet></router-outlet>

    So the router will be render inside this router-outlet.

    The contact list component:

    import { Component, OnInit } from '@angular/core';
    import {ContactDetailComponent} from "./contact-detail-component/contact-detail-component.component";
    import {ROUTER_DIRECTIVES} from "@angular/router";
    
    @Component({
      moduleId: module.id,
      directives: [ContactDetailComponent, ROUTER_DIRECTIVES],
      selector: 'app-contact-list-component',
      templateUrl: 'contact-list-component.component.html',
      styleUrls: ['contact-list-component.component.css']
    })
    export class ContactListComponent implements OnInit {
    
      contacts: Array<Object>;
      constructor() {
        this.contacts = [
          {
            id: 0,
            name: "Zhentian",
            position: "Lead developer"
          },
          {
            id: 1,
            name: "ABC",
            position: "Junior developer"
          },
          {
            id: 2,
            name: "Herry",
            position: "Productor Owner"
          },
          {
            id: 3,
            name: "Janne",
            position: "Master"
          },
          {
            id: 4,
            name: "Jonne",
            position: "Backend developer"
          }
        ];
      }
      ngOnInit() {
      }
    
    }

    Notice that, we have inject the ROUTER_DIRECTIVE for later use.

    Template for the contact list component:

    <h2>Contacts</h2>
    <ul>
      <li *ngFor="let contact of contacts">
        <a [routerLink]="['/contacts', contact.id]">{{contact.name}}</a> |
        <a routerLink="/contacts/{{contact.id}}">{{contact.name}}</a>
      </li>
    </ul>

    To navigate to other router compoent, we need to use 'routerLink', notice there is tow ways to use 'routerLink':

    <a [routerLink]="['/contacts', contact.id]">{{contact.name}}</a> 

    or

    <a routerLink="/contacts/{{contact.id}}">{{contact.name}}</a>

    For the contact detail compoent, we want to receive an 'id', which can later fetch the data from server.

    To get the param which be passed in , we need to use 'ActivedRoute':

    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute } from '@angular/router';
    
    @Component({
      moduleId: module.id,
      selector: 'app-contact-detail-component',
      templateUrl: 'contact-detail-component.component.html',
      styleUrls: ['contact-detail-component.component.css']
    })
    export class ContactDetailComponent implements OnInit {
    
      id: number;
      constructor(private route: ActivatedRoute) {
        this.id = this.route.snapshot.params['id'];
      }
    
      ngOnInit() {
      }
    
    }

    Here we use 'snapshot', this means we don't care about the later router params changes, we just need to get id and that's it. It is a cheaper solution.

    Another way to do it is using ObservableActivatedRoute comes with a params property which is an Observable. To access the contact id, all we have to do is to subscribe to the parameters Observablechanges. 

    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute } from '@angular/router';
    
    @Component({
      moduleId: module.id,
      selector: 'app-contact-detail-component',
      templateUrl: 'contact-detail-component.component.html',
      styleUrls: ['contact-detail-component.component.css']
    })
    export class ContactDetailComponent implements OnInit {
    
      id: number;
      constructor(private route: ActivatedRoute) {
      }
    
      ngOnInit() {
        this.route.params
          .map(params => params['id'])
          .subscribe((id) => {
            this.id = id;
          });
      }
    
    }

    But in this case, use snapshot is prefect fine, since id would change later.

    Original Actical: http://blog.thoughtram.io/angular/2016/06/14/routing-in-angular-2-revisited.html

    Github: https://github.com/zhentian-wan/hello-angular2

  • 相关阅读:
    WP&Win10仿微信消息框代码分享
    Windows编程中回调函数的使用心得(MFC篇)
    进程间通信之WM_COPYDATA方式反思,回顾和总结
    华为的最新的两道算法设计题
    Python中3元运算符的实现
    Python Logging 模块研究
    LINUX下CPU Load Average的一点研究
    64位系统下,一个32位的程序究竟可以申请到多少内存,4GB还是更多?(一)
    Pyscripter 不能正确调用另一文件中模块的问题的解析(Internal Engine 和 Remote Engine)
    Django 最佳实践
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5693753.html
Copyright © 2011-2022 走看看