为了应对未来的趋势,及时赶上下一趟互联网技术,我最近也在通过具体项目研究angular2,首先必须要吐槽的是,学习angular2的成本本身不高,但是一堆的工具、配置实在让人 很是焦灼,就像asp.net core一样,所有的东西都在向同样的方向迈进:尽量使用已经造好的轮子,而不是自己再弄一个。

当然,统一是好的,但是对于对前端不是太敏感的我来说,还是挑战不小,这就要求我要学好angular2,必须要熟悉一系列的工具链。加油。

今天要说的是一个可以说我遇到的很诡异的问题,我在angular1上进行了相同的尝试,没有发现这个问题,但是在angular2上发现了,我将使用场景还原一下,当然我只是抽取其中的一部分,希望有人遇到或知道如何解决回复一下,当然如果我找到答案,会注明。

背景:我通过angular2 下叫ng2,的路由来实现视图的导航,我使用官方文档英雄列表来说明。我从英雄列表页面通过路由导航到具体的详情页面,但是我准备实现从详情页面导航到列表页面时出现的问题。

我自己尝试了几种实现方式:

  1. window.history.back():通过浏览器的回退实现
  2. 通过router.navigate(['/heros']).其中router通过构造函数进行注入

我要说明的问题就是通过第二种实现。

  1. 步骤1:新建index.html页面,没有什么特别的地方,只是设置了ng2的启动页面

     <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>guozhiqi</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" type="text/css" href="node_modules/primeng/resources/themes/delta/theme.css" />
    <link rel="stylesheet" type="text/css" href="node_modules/font-awesome/css/font-awesome.css" />
    <link rel="stylesheet" type="text/css" href="node_modules/primeng/resources/primeng.min.css" />
    <base href="/">
    </head>
    <body> <my-app>
    Loading...
    </my-app> <script src="node_modules/core-js/client/shim.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/systemjs/dist/system.js"></script>
    <script src="systemjs.config.js"></script>
    <script>
    System.import('app').catch(function (err) {
    console.error(err);
    })
    </script> </body>
    </html>
  2. 步骤2:新建app文件夹,并且添加main.ts页面
     /**
    * Created by guozhiqi on 2016/9/19.
    */
    import {platformBrowserDynamic}from '@angular/platform-browser-dynamic';
    import {AppModule}from './app.module';
    import {RouterModule}from '@angular/router'; const platform=platformBrowserDynamic();
    platform.bootstrapModule(AppModule);

    添加ng2的启动模块AppModule

  3. 在app文件夹添加app.module.ts文件
      
     import './rxjs-extensions';
    
     import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http'; // Imports for loading & configuring the in-memory web api
    import { InMemoryWebApiModule } from 'angular2-in-memory-web-api';
    import { InMemoryDataService } from './in-memory-data.service'; import { AppComponent } from './app.component';
    import { DashboardComponent } from './dashboard.component';
    import { HerosComponent } from './heros.component';
    import { HeroDetailComponent } from './hero-detail.component';
    import { HeroService } from './hero.service';
    import { HeroSearchComponent } from './hero-search.component';
    import { routing } from './app.routing';
    import {RouterModule,Router}from '@angular/router'; @NgModule({
    imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    InMemoryWebApiModule.forRoot(InMemoryDataService),RouterModule,
    routing
    ],
    declarations: [
    AppComponent,
    DashboardComponent,
    HeroDetailComponent,
    HerosComponent,
    HeroSearchComponent
    ],
    providers: [
    HeroService
    ],
    bootstrap: [ AppComponent ]
    })
    export class AppModule {
    } /*
    Copyright 2016 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license
    */

    重点是我们导入了RoutingModule模块

  4. 添加路由配置app.routing.ts
     import {ModuleWithProviders}from '@angular/core';
    import {Routes, RouterModule}from '@angular/router';
    import {HerosComponent}from './heros.component';
    import {DashboardComponent}from './dashboard.component';
    import {HeroDetailComponent}from './hero-detail.component';
    const appRoutes:Routes = [
    {
    path: 'heros',
    component: HerosComponent
    },
    {
    path:'dashboard',
    component:DashboardComponent
    }, {
    path:'detail/:id',
    component:HeroDetailComponent
    },
    {
    path:'',
    redirectTo: '/dashboard',
    pathMatch: 'full'
    },
    {
    path:'**',
    component:DashboardComponent
    }
    ] export const routing:ModuleWithProviders=RouterModule.forRoot(appRoutes);
  5. 添加英雄列表页面heros.component.ts
     /**
    * Created by guozhiqi on 2016/9/19.
    */
    import {Component, OnInit}from '@angular/core';
    import {Title}from '@angular/platform-browser';
    import {ButtonModule}from 'primeng/primeng';
    import {Hero}from './hero';
    import {HeroService} from "./hero.service";
    import {HeroDetailComponent}from './hero-detail.component';
    import {Router}from '@angular/router'; @Component({
    selector: "my-heros",
    templateUrl: 'app/heros.component.html',
    styleUrls: ['app/heros.component.css']
    }) export class HerosComponent implements OnInit {
    heros:Hero[];
    selectedHero:Hero; ngOnInit():void {
    this.getHeros();
    } getHeros():void {
    this.heroService.getHeroes().then(heros=>this.heros = heros);
    } onSelect(hero:Hero) {
    this.selectedHero = hero;
    } gotoDetail() {
    35 this.router.navigate(['/detail', this.selectedHero.id]);
    36 } add(name:string):void {
    name = name.trim();
    if (!name) {
    return;
    } this.heroService.create(name)
    .then(hero=>{
    this.heros.push(hero);
    this.selectedHero=null;
    });
    } delete(hero:Hero):void
    {
    this.heroService.delete(hero.id)
    .then(()=>{
    this.heros=this.heros.filter(h=>h!==hero);
    if(this.selectedHero===hero)
    {
    this.selectedHero=null;
    }
    })
    } constructor(private router:Router, private titleService:Title, private heroService:HeroService) {
    this.titleService.setTitle("HeroList");
    } }

    重点就出现在我们通过构造函数注入的Router上,我们的英雄列表通过router.navigate(

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

    )来导航到了详情页面,请注意,router是通过构造函数注入

  6. 详情页面组件代码
     /**
    * Created by guozhiqi on 2016/9/19.
    */
    import {Component, Input, OnInit}from'@angular/core';
    import {ActivatedRoute, Params, Router}from'@angular/router';
    import {HeroService}from './hero.service';
    import {Title}from '@angular/platform-browser';
    import {Hero} from "./Hero";
    import from = require("core-js/fn/array/from"); @Component({
    selector: 'my-hero-detail',
    templateUrl: 'app/hero-detail.component.html',
    styleUrls: ['app/hero-detail.component.css'],
    }) export class HeroDetailComponent implements OnInit {
    hero:Hero;
    currentDate:Date;
    private router:Router; constructor(private heroService:HeroService,
    private route:ActivatedRoute,
    router:Router,
    private title:Title) {
    this.currentDate = new Date(); this.title.setTitle("hero-detail");
    } ngOnInit():void {
    this.route.params.forEach((params:Params)=> {
    let id = +params['id'];
    this.heroService.getHero(id).then(hero=>this.hero = hero);
    });
    } goBack():void {
    39 window.history.back();
    40 // this.router.navigate(['/heros']);
    41
    42 } save():void {
    this.heroService.update(this.hero).then(this.goBack);
    }
    }

    重点是详情页面的goBack()方法,我本来准备通过路由的navigate方法 来实现导航,并且router是通过构造函数注入,但是我在使用时this.router会为null,导致我无法通过这种方式实现页面跳转。

其实我想说的这个倒不是ng2的bug,可能有些地方没有设置成功,之所以说是bug,而是因为官方没有提供具体的详细信息。

有知晓的麻烦回复一下,我相信如果要使用页面跳转,肯定会用到。

更详细的内容可以参考官方的英雄列表。

应该是Angular2的一个bug?的更多相关文章

  1. Tomcat一个BUG造成CLOSE_WAIT

    之前应该提过,我们线上架构整体重新架设了,应用层面使用的是Spring Boot,前段日子因为一些第三方的原因,略有些匆忙的提前开始线上的内测了.然后运维发现了个问题,服务器的HTTPS端口有大量的C ...

  2. MySQL关于exists的一个bug

    今天碰到一个很奇怪的问题,关于exists的, 第一个语句如下: SELECT ) FROM APPLY t WHERE EXISTS ( SELECT r.APPLY_ID FROM RECORD ...

  3. 由一个bug引发的SQLite缓存一致性探索

    问题 我们在生产环境中使用SQLite时中发现建表报“table xxx already exists”错误,但DB文件中并没有该表.后面才发现这个是SQLite在实现过程中的一个bug,而这个bug ...

  4. Win10系统菜单打不开问题的解决,难道是Win10的一个Bug ?

    Win10左下角菜单打不开,好痛苦,点击右下角的时间也没反应,各种不爽,折磨了我好几天,重装又不忍心,实在费劲,一堆开发环境要安装,上网找了很多方法都不适用.今天偶然解决了,仔细想了下,难道是Win1 ...

  5. 你可能不知道的 NaN 以及 underscore 1.8.3 _.isNaN 的一个 BUG

    这篇文章并不在我的 underscore 源码解读计划中,直到 @pod4g 同学回复了我的 issue(详见 https://github.com/hanzichi/underscore-analy ...

  6. 标准模板库(STL)的一个 bug

    今天敲代码的时候遇到 STL 的一个 bug,与 C++ 的类中的 const 成员变量有关.什么,明明提供了默认的构造函数和复制构造函数,竟然还要类提供赋值运算符重载.怎么会这样? 测试代码 Tes ...

  7. 是uibutton跟tableviewcell同步使用一个bug

    这个问题是uibutton跟tableviewcell同步使用一个bug,不关delay一点毛事,证据就是点击事件没问题,so,搜到一个方法解决了这个问题.uibutton分类symbian2+ios ...

  8. 在chrome下-webkit-box布局的一个bug

    chrome,也就是webkit内核下作的检测, chrome版本是40, -webkit-box这种布局在移动端用的比较多,主要是因为pc端的浏览器内核参差不齐. 因为在写HTML的时候看上了-we ...

  9. 关于MySQL count(distinct) 逻辑的一个bug【转】

    本文来自:http://dinglin.iteye.com/blog/1976026#comments 背景 客户报告了一个count(distinct)语句返回结果错误,实际结果存在值,但是用cou ...

随机推荐

  1. 百度MIP移动页面加速——不只是CDN

    MIP是用CDN做加速的么?准确答案是:是,但不只是. MIP全称Mobile Instant Pages,移动网页加速器,是百度提出的页面加速解决方案.MIP从前端渲染和页面网络传输两方面进行优化, ...

  2. 一个免费的、跨平台的、开源音频编辑器Audacity

    Audacity 是一个免费的开源程序,用于编辑音频录制.它可在多个平台(windows/linux)上运行.Audacity 基于 GUI,是一个具有多种选项的强大程序.它支持您录制各种类型的声音. ...

  3. LeetCode-5LongestPalindromicSubstring(C#)

    # 题目 5. Longest Palindromic Substring Given a string S, find the longest palindromic substring in S. ...

  4. jsp前端实现分页代码

    前端需要订一page类包装,其参数为 private Integer pageSize=10; //每页记录条数=10 private Integer totalCount; //总记录条数 priv ...

  5. (系统架构)标准Web系统的架构分层

    标准Web系统的架构分层 1.架构体系分层图 在上图中我们描述了Web系统架构中的组成部分.并且给出了每一层常用的技术组件/服务实现.需要注意以下几点: 系统架构是灵活的,根据需求的不同,不一定每一层 ...

  6. 怎么让网站在本地支持SSL?

    打开vs,点击项目,查看属性,打开ssl 如果有什么危险提示,就允许 右击项目,选择属性 运行项目

  7. .NET平台开源项目速览(14)最快的对象映射组件Tiny Mapper

    好久没有写文章,工作甚忙,但每日还是关注.NET领域的开源项目.五一休息,放松了一下之后,今天就给大家介绍一个轻量级的对象映射工具Tiny Mapper:号称是.NET平台最快的对象映射组件.那就一起 ...

  8. 【开源】.net 分布式架构之监控平台

    开源地址:http://git.oschina.net/chejiangyi/Dyd.BaseService.Monitor .net 简单监控平台,用于集群的性能监控,应用耗时监控管理,统一日志管理 ...

  9. jQuery.Ajax IE8 无效(CORS)

    今天在开发的时候,遇到一个问题,$.get()在 IE8 浏览器不起作用,但 Chrome,Firefox 却是可以的,网上资料很多,最后发现是 IE8 默认不支持 CORS 请求,需要手动开启下: ...

  10. [修正] Firemonkey TFrame 存档后,下次载入某些事件连结会消失(但源码还在)

    问题:Firemonkey TFrame 存档后,下次载入某些事件连结会消失(但源码还在) 解决:(暂时方法) type TTestFrame = class(TFrame) public const ...