ng2学习初体验

来源:互联网 发布:淘宝全屏店招在线制作 编辑:程序博客网 时间:2024/06/06 07:20

今天试着跑了一下项目 https://github.com/AngularClass/angular2-webpack-starter
不出意外地踩了几个坑
将项目代码下载到本地后
按照项目提示,事先安装好以下几个依赖包(当然首先要有个node)

* webpack (npm install --global webpack)* webpack-dev-server (npm install --global webpack-dev-server)* karma (npm install --global karma-cli)* protractor (npm install --global protractor)* typescript (npm install --global typescript)

然后cd进入项目
执行命令行cnpm install,安装完毕后,再执行
npm run server

最后打开浏览器,输入locahost:3000
如果没有意外,就可以看到下面这个华丽丽的界面了。。。
界面

然后模仿demo写一个test模块
设置新模块的路由时,需要修改的文件有三个:app.module.ts,app.routes.ts,app.component.ts

(1) 创建一个新的模块test文件结构
(2) index.ts

export * from './test.component';

(3) test.component.ts

import { Component } from '@angular/core';import { ActivatedRoute } from '@angular/router';/** We're loading this component asynchronously* We are using some magic with es6-promise-loader that will wrap the module with a Promise* see https://github.com/gdi2290/es6-promise-loader for more info*/console.log('`Test` component loaded asynchronously');@Component({  selector: 'test',  styles: [`  `],  template: `    <h1>Test</h1>    <div>      For hot module reloading run      <pre>npm run start:hmr</pre>    </div>    <div>      <h3>        patrick@AngularClass.com      </h3>    </div>    <pre>this.localState = {{ localState | json }}</pre>  `})export class Test {  localState: any;  constructor(public route: ActivatedRoute) {  }  ngOnInit() {    this.route      .data      .subscribe((data: any) => {        // your resolved data from route        this.localState = data.yourData;      });    console.log('hello `Test` component');    // static data that is bundled    // var mockData = require('assets/mock-data/mock-data.json');    // console.log('mockData', mockData);    // if you're working with mock data you can also use http.get('assets/mock-data/mock-data.json')    this.asyncDataWithWebpack();  }  asyncDataWithWebpack() {    // you can also async load mock data with 'es6-promise-loader'    // you would do this if you don't want the mock-data bundled    // remember that 'es6-promise-loader' is a promise    setTimeout(() => {      System.import('../../assets/mock-data/mock-data.json')        .then(json => {          console.log('async mockData', json);          this.localState = json;        });    });  }}

(4) test.spec.ts

import { ActivatedRoute, Data } from '@angular/router';import { Component } from '@angular/core';import { inject, TestBed } from '@angular/core/testing';// Load the implementations that should be testedimport { Test } from './test.component';describe('Test', () => {  // provide our implementations or mocks to the dependency injector  beforeEach(() => TestBed.configureTestingModule({    providers: [      // provide a better mock      {        provide: ActivatedRoute,        useValue: {          data: {            subscribe: (fn: (value: Data) => void) => fn({              yourData: 'yolo'            })          }        }      },      Test    ]  }));  it('should log ngOnInit', inject([Test], (test: Test) => {    spyOn(console, 'log');    expect(console.log).not.toHaveBeenCalled();    test.ngOnInit();    expect(console.log).toHaveBeenCalled();  }));});

(5) 修改app.module.ts

import { Home } from './home';import { About } from './about';import { Test } from './test';//新增import { NoContent } from './no-content';import { XLarge } from './home/x-large';

(6) 修改app.routes.ts

import { Routes, RouterModule } from '@angular/router';import { Home } from './home';import { About } from './about';import { Test } from './test';//新增import { NoContent } from './no-content';import { DataResolver } from './app.resolver';export const ROUTES: Routes = [  { path: '',      component: Home },  { path: 'home',  component: Home },  { path: 'about', component: About },  { path: 'test', component: Test },//新增  {    path: 'detail', loadChildren: () => System.import('./+detail')  },  { path: '**',    component: NoContent },];

(7) 修改app.component.ts

template: `    <nav>      <span>        <a [routerLink]=" ['./'] ">          Index        </a>      </span>      |      <span>        <a [routerLink]=" ['./home'] ">          Home        </a>      </span>      |      <span>        <a [routerLink]=" ['./detail'] ">          Detail        </a>      </span>      |      <span>        <a [routerLink]=" ['./about'] ">          About        </a>      </span>      |      <span>        <a [routerLink]=" ['./test'] ">          Test        </a>      </span>    </nav>    <main>      <router-outlet></router-outlet>    </main>    <pre class="app-state">this.appState.state = {{ appState.state | json }}</pre>    <footer>      <span>WebPack Angular 2 Starter by <a [href]="url">@AngularClass</a></span>      <div>        <a [href]="url">          <img [src]="angularclassLogo" width="25%">        </a>      </div>    </footer>  `

下面是遇到的几个问题:

1. 在ts的constructor构造函数中使用this.xxx,webstorm文件提示undefined错误(未知)2. npm buidl:prod报错——已解决:https://github.com/AngularClass/angular2-webpack-starter/issues/1048

github截图

3. ngFor

之前看的教程http://www.hubwiz.com/class/5599d367a164dd0d75929c76上是这样用的

<ul>   <li *ng-for="#film of films">{{film}}</li></ul>

但是看到最新的官网https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html上,是这样的:

 <li *ngFor="let item of items; let i = index; trackBy: trackByFn">...</li>

这个教程应该是去年的= =。。。所以还是要多看看官网啊。

0 0
原创粉丝点击