開始的前提是現在你的機械上安裝node環境,安裝node環境===》點擊打開鏈接
我使用的環境是: mac node(v.6.10.0) npm(3.10.10)
一:確保node環境已經安裝,然後全局安裝angular-CLI輸入:
npm install -g @angular/cli
or
sudo npm install -g @angular/cli
可能需要一些時間,等待安裝完成。
二:創建新的應用,輸入:
ng new my-app
my-app爲應用的名稱,你可以隨意更改它。
三:啓動應用,輸入:
cd my-app
ng serve
ng serve命令會啓動應用,監聽文件變化,當文件更改時會重新構建此應用。到此本地開發環境就準備好了。
我們創建一個hero服務,在app下創建一個hero.service.ts文件
import { Injectable } from '@angular/core';
@Injectable()
export class HeroService {
}
創建一個方法來獲取hero數據,數據都是從服務器上獲取的,這裏我們使用模擬數據源,在app下創建一個hero.ts文件:
export class Hero{
id:number;
name:string;
}
創建mock-heroes.ts文件模擬數據:
import { Hero } from './hero';
export const HEROES: Hero[] = [
{id: 11, name: 'Mr. Nice'},
{id: 12, name: 'Narco'},
{id: 13, name: 'Bombasto'},
{id: 14, name: 'Celeritas'},
{id: 15, name: 'Magneta'},
{id: 16, name: 'RubberMan'},
{id: 17, name: 'Dynama'},
{id: 18, name: 'Dr IQ'},
{id: 19, name: 'Magma'},
{id: 20, name: 'Tornado'}
];
在hero.service文件中添加一個getHeroes方法返回heroes列表:
import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class HeroService {
getHeroes(): Promise<Hero[]> {
return Promise.resolve(HEROES);
}
}
使用hero.service
在app.component.ts文件中引入服務:
import { HeroService } from './hero.service';
注入服務
constructor(private heroService: HeroService) { }
我們還得註冊一個service提供商來告訴注入器如何創建service:
providers: [HeroService]
在app.component中使用服務:
getHeroes(): void {
this.heroService.getHeroes().then(heroes => this.heroes = heroes);
}
完整的代碼:
import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'my-app',
template: `
<ul class="heroes">
<li *ngFor="let hero of heroes"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
`,
providers: [HeroService]
})
export class AppComponent implements OnInit {
title = 'Tour of Heroes';
heroes: Hero[];
selectedHero: Hero;
constructor(private heroService: HeroService) { }
getHeroes(): void {
this.heroService.getHeroes().then(heroes => this.heroes = heroes);
}
ngOnInit(): void {
this.getHeroes();
}
onSelect(hero: Hero): void {
this.selectedHero = hero;
}
}
可以使用bootstrap點擊打開鏈接