應該是Angular2的一個bug?


     為了應對未來的趨勢,及時趕上下一趟互聯網技術,我最近也在通過具體項目研究angular2,首先必須要吐槽的是,學習angular2的成本本身不高,但是一堆的工具、配置實在讓人 很是焦灼,就像asp.net core一樣,所有的東西都在向同樣的方向邁進:盡量使用已經造好的輪子,而不是自己再弄一個。

     當然,統一是好的,但是對於對前端不是太敏感的我來說,還是挑戰不小,這就要求我要學好angular2,必須要熟悉一系列的工具鏈。加油。

 

今天要說的是一個可以說我遇到的很詭異的問題,我在angular1上進行了相同的嘗試,沒有發現這個問題,但是在angular2上發現了,我將使用場景還原一下,當然我只是抽取其中的一部分,希望有人遇到或知道如何解決回復一下,當然如果我找到答案,會注明。

    背景:我通過angular2 下叫ng2,的路由來實現視圖的導航,我使用官方文檔英雄列表來說明。我從英雄列表頁面通過路由導航到具體的詳情頁面,但是我准備實現從詳情頁面導航到列表頁面時出現的問題。

  我自己嘗試了幾種實現方式:

  1.  window.history.back():通過瀏覽器的回退實現
  2. 通過router.navigate(['/heros']).其中router通過構造函數進行注入

我要說明的問題就是通過第二種實現。

  1.  步驟1:新建index.html頁面,沒有什么特別的地方,只是設置了ng2的啟動頁面
     1 <!DOCTYPE html>
     2     <html lang="en">
     3     <head>
     4         <meta charset="UTF-8">
     5         <title>guozhiqi</title>
     6         <meta name="viewport" content="width=device-width,initial-scale=1">
     7         <link rel="stylesheet" type="text/css" href="node_modules/primeng/resources/themes/delta/theme.css" />
     8         <link rel="stylesheet" type="text/css" href="node_modules/font-awesome/css/font-awesome.css" />
     9         <link rel="stylesheet" type="text/css" href="node_modules/primeng/resources/primeng.min.css" />
    10         <base href="/">
    11     </head>
    12     <body>
    13     
    14     <my-app>
    15         Loading...
    16     </my-app>
    17     
    18     <script src="node_modules/core-js/client/shim.js"></script>
    19     <script src="node_modules/reflect-metadata/Reflect.js"></script>
    20     <script src="node_modules/zone.js/dist/zone.js"></script>
    21     <script src="node_modules/systemjs/dist/system.js"></script>
    22     <script src="systemjs.config.js"></script>
    23     <script>
    24         System.import('app').catch(function (err) {
    25             console.error(err);
    26         })
    27     </script>
    28     
    29     </body>
    30     </html>

     

  2. 步驟2:新建app文件夾,並且添加main.ts頁面
    1 /**
    2  * Created by guozhiqi on 2016/9/19.
    3  */
    4 import {platformBrowserDynamic}from '@angular/platform-browser-dynamic';
    5 import {AppModule}from './app.module';
    6 import {RouterModule}from '@angular/router';
    7 
    8 const  platform=platformBrowserDynamic();
    9 platform.bootstrapModule(AppModule);

    添加ng2的啟動模塊AppModule

  3. 在app文件夾添加app.module.ts文件
      
     1 import './rxjs-extensions';
     2 
     3 import { NgModule }      from '@angular/core';
     4 import { BrowserModule } from '@angular/platform-browser';
     5 import { FormsModule }   from '@angular/forms';
     6 import { HttpModule }    from '@angular/http';
     7 
     8 // Imports for loading & configuring the in-memory web api
     9 import { InMemoryWebApiModule } from 'angular2-in-memory-web-api';
    10 import { InMemoryDataService }  from './in-memory-data.service';
    11 
    12 import { AppComponent }         from './app.component';
    13 import { DashboardComponent }   from './dashboard.component';
    14 import { HerosComponent }      from './heros.component';
    15 import { HeroDetailComponent }  from './hero-detail.component';
    16 import { HeroService }          from './hero.service';
    17 import { HeroSearchComponent }  from './hero-search.component';
    18 import { routing }              from './app.routing';
    19 import {RouterModule,Router}from '@angular/router';
    20 
    21 @NgModule({
    22     imports: [
    23         BrowserModule,
    24         FormsModule,
    25         HttpModule,
    26         InMemoryWebApiModule.forRoot(InMemoryDataService),RouterModule,
    27         routing
    28     ],
    29     declarations: [
    30         AppComponent,
    31         DashboardComponent,
    32         HeroDetailComponent,
    33         HerosComponent,
    34         HeroSearchComponent
    35     ],
    36     providers: [
    37         HeroService
    38     ],
    39     bootstrap: [ AppComponent ]
    40 })
    41 export class AppModule {
    42 }
    43 
    44 
    45 /*
    46  Copyright 2016 Google Inc. All Rights Reserved.
    47  Use of this source code is governed by an MIT-style license that
    48  can be found in the LICENSE file at http://angular.io/license
    49  */

    重點是我們導入了RoutingModule模塊

  4. 添加路由配置app.routing.ts
     1 import {ModuleWithProviders}from '@angular/core';
     2 import {Routes, RouterModule}from '@angular/router';
     3 import {HerosComponent}from './heros.component';
     4 import {DashboardComponent}from './dashboard.component';
     5 import {HeroDetailComponent}from './hero-detail.component';
     6 const appRoutes:Routes = [
     7     {
     8         path: 'heros',
     9         component: HerosComponent
    10     },
    11     {
    12         path:'dashboard',
    13         component:DashboardComponent
    14     },
    15 
    16     {
    17         path:'detail/:id',
    18         component:HeroDetailComponent
    19     },
    20     {
    21         path:'',
    22         redirectTo: '/dashboard',
    23         pathMatch: 'full'
    24     },
    25     {
    26         path:'**',
    27         component:DashboardComponent
    28     }
    29 ]
    30 
    31 export const  routing:ModuleWithProviders=RouterModule.forRoot(appRoutes);

     

  5. 添加英雄列表頁面heros.component.ts
     1 /**
     2  * Created by guozhiqi on 2016/9/19.
     3  */
     4 import {Component, OnInit}from '@angular/core';
     5 import {Title}from '@angular/platform-browser';
     6 import {ButtonModule}from 'primeng/primeng';
     7 import {Hero}from './hero';
     8 import {HeroService} from "./hero.service";
     9 import {HeroDetailComponent}from './hero-detail.component';
    10 import {Router}from '@angular/router';
    11 
    12 @Component({
    13     selector: "my-heros",
    14     templateUrl: 'app/heros.component.html',
    15     styleUrls: ['app/heros.component.css']
    16 })
    17 
    18 export class HerosComponent implements OnInit {
    19     heros:Hero[];
    20     selectedHero:Hero;
    21 
    22     ngOnInit():void {
    23         this.getHeros();
    24     }
    25 
    26     getHeros():void {
    27         this.heroService.getHeroes().then(heros=>this.heros = heros);
    28     }
    29 
    30     onSelect(hero:Hero) {
    31         this.selectedHero = hero;
    32     }
    33 
    34     gotoDetail() {
    35         this.router.navigate(['/detail', this.selectedHero.id]);
    36     }
    37 
    38     add(name:string):void {
    39         name = name.trim();
    40         if (!name) {
    41             return;
    42         }
    43 
    44         this.heroService.create(name)
    45             .then(hero=>{
    46                 this.heros.push(hero);
    47                 this.selectedHero=null;
    48             });
    49     }
    50 
    51     delete(hero:Hero):void
    52     {
    53         this.heroService.delete(hero.id)
    54             .then(()=>{
    55                 this.heros=this.heros.filter(h=>h!==hero);
    56                 if(this.selectedHero===hero)
    57                 {
    58                     this.selectedHero=null;
    59                 }
    60             })
    61     }
    62 
    63     constructor(private  router:Router, private titleService:Title, private heroService:HeroService) {
    64         this.titleService.setTitle("HeroList");
    65     }
    66 
    67 
    68 }

    重點就出現在我們通過構造函數注入的Router上,我們的英雄列表通過router.navigate(

    ['/detail', this.selectedHero.id]

    )來導航到了詳情頁面,請注意,router是通過構造函數注入

  6. 詳情頁面組件代碼
     1 /**
     2  * Created by guozhiqi on 2016/9/19.
     3  */
     4 import {Component, Input, OnInit}from'@angular/core';
     5 import {ActivatedRoute, Params, Router}from'@angular/router';
     6 import {HeroService}from './hero.service';
     7 import {Title}from '@angular/platform-browser';
     8 import {Hero} from "./Hero";
     9 import from = require("core-js/fn/array/from");
    10 
    11 @Component({
    12     selector: 'my-hero-detail',
    13     templateUrl: 'app/hero-detail.component.html',
    14     styleUrls: ['app/hero-detail.component.css'],
    15 })
    16 
    17 export class HeroDetailComponent implements OnInit {
    18     hero:Hero;
    19     currentDate:Date;
    20     private router:Router;
    21 
    22     constructor(private heroService:HeroService,
    23                 private  route:ActivatedRoute,
    24                 router:Router,
    25                 private  title:Title) {
    26         this.currentDate = new Date();
    27 
    28         this.title.setTitle("hero-detail");
    29     }
    30 
    31     ngOnInit():void {
    32         this.route.params.forEach((params:Params)=> {
    33             let id = +params['id'];
    34             this.heroService.getHero(id).then(hero=>this.hero = hero);
    35         });
    36     }
    37 
    38     goBack():void {
    39         window.history.back();
    40         //   this.router.navigate(['/heros']);
    41 
    42     }
    43 
    44     save():void {
    45         this.heroService.update(this.hero).then(this.goBack);
    46     }
    47 }

    重點是詳情頁面的goBack()方法,我本來准備通過路由的navigate方法 來實現導航,並且router是通過構造函數注入,但是我在使用時this.router會為null,導致我無法通過這種方式實現頁面跳轉。

其實我想說的這個倒不是ng2的bug,可能有些地方沒有設置成功,之所以說是bug,而是因為官方沒有提供具體的詳細信息。

有知曉的麻煩回復一下,我相信如果要使用頁面跳轉,肯定會用到。

 更詳細的內容可以參考官方的英雄列表。

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM