AngularJS 2 学习

Angular JS 2 官文: https://angular.io/docs/ts/latest/quickstart.html

貌似需要翻墙…

本文以 TypeScript 为例进行学习.

5 分钟快速开始

基础教程

[代码片段]

// hero.ts
export class Hero {
    id: number;
    name: string;
}

// app.ts
import { Component } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: "sd-student",
    template: `<ul>
        <li *ngFor="let hero of heros" (click)="onSelect(hero)" [class.selected]="hero === selectedHero"><span> {{ hero.name }} </span></li>
        </ul>
        <br>
        <div *ngIf="selectedHero">
          <h2>{{selectedHero.name}} details!</h2>
          <div><label>id: </label>{{selectedHero.id}}</div>
          <div>
            <label>name: </label>
            <input [(ngModel)]="selectedHero.name" placeholder="name"/>
          </div>
        </div>
        {{ name }}
        <input [(ngModel)]="name" />`,
    styleUrls: ['student.component.css']
})
export class StudentComponent {
    title: "";
    name: "OnO";
    selectedHero: Hero;
    heros: Hero[] = [{id:1, name:"OnO"},{id:2, name:"Bob"}];
    onSelect(hero: Hero):void {
        console.log(hero);
        this.selectedHero = hero;
    }
}
  1. 绑定

  2. 双向绑定

    <input [(ngModel)]=”selectedHero.name” />

  3. 类中数据源

    selectedHero: Hero

  4. 条件判断

    *ngIf=”selectedHero”

  5. 循环

    *ngFor=”let hero of heros”

[代码片段]

// hero-detail.ts
import { Component, Input } from '@angular/core';

inport { Hero } from "./hero"

@Component({
    selector: "sd-hero-detail",
    template: `
      <div *ngIf="hero">
      <h2>{{hero.name}} details!</h2>
      <div><label>id: </label>{{hero.id}}</div>
      <div>
        <label>name: </label>
        <input [(ngModel)]="hero.name" placeholder="name"/>
      </div>
    </div>
    `
})
export class HeroDetailComponent {
    @Input()
    hero: Hero;
}
  1. 使用 Input 定义数据源

    @Input
    hero: Hero;

  2. 定义与 selector 相同的标签来存放内容

  3. 绑定 Input 数据源到 selector

    <sd-hero-detail [hero]=”selectedHero”>

[代码片段]

// admin-login.service.ts
import { Injectable } from '@angular/core';
import { AdminUserInfo } from "./interfaces";

@Injectable()
export class AdminLoginService {
  login(username:string, password:string, remember:boolean): AdminUserInfo {
    if (username == "ono" && password == "xxyyzz") {
      return new AdminUserInfo();
    }
    return null;
  }
}

// admin-login.component.ts
import { AdminLoginService } from "./login-service/admin-login.service"

export class AdminLoginComponent implements OnInit {
  username: string;
  password: string;
  remember: boolean;

  ngOnInit(): void {
  }

  constructor(public adminloginservice: AdminLoginService) {}
}

// admin-login.html

adminloginservice.login() 即可~~

此时会报错:

EXCEPTION: No provider for AdminUserInfo! (AppComponent -> AdminUserInfo)

在入口处, 添加 providers: [AdminUserInfo] 即可

  1. 服务定义及使用

定义

@Injectable()
export class xx {
  // 同步
  getData(): string{
    return "123";
  }
  // 异步
  getDataAsync(): Promise<string>{
    return Promise.resolve("123");
  }
}

使用

export class yy implements OnInit {
  ngOnInit(): void {
    this.getData();
    // OR this.getDataAsync();
  }
  constructor(private a: xx){}
  // 同步封装
  getData(): void{
    this.data = this.a.getData();
  }
  // 异步封装
  getDataAsync(): void{
    this.a.getDataAsync().then(d => this.data = d);
  }
}

此处要在入口处的 Component 中注入 providers xx.

  1. 使用 ngOnInit 进行启动后适当时间调用内部方法.

[代码片段]

注册 Http 服务

import {HttpModule} from '@angular/http';

imports: [ HttpModule ],

providers: [ HeroService ],

实现 Http 服务

import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';


private headers = new Headers({'Content-Type': 'application/json'});
private heroUrl = 'app/heroes';

constructor(private http: Http) {}

private handleError(error: any): Promise<any> {
  console.error('An error occurred', error); // for demo purposes only
  return Promise.reject(error.message || error);
}

getHeroes(): Promise<Hero[]> {
  return this.http.get(this.heroesUrl)
    .toPromise()
    .then(resp => resp.json().data as Hero[])
    .catch(this.handleError);
}

getHero(id: number): Promise<Hero> {
  return this.getHeroes()
    .then(heroes => heroes.find(hero => hero.id === id));
}

addHero(name: string): Promise<Hero> {
  return this.http.post(this.heroesUrl, JSON.stringify({name: name}), {header: this.headers})
    .toPromise()
    .then(res => res.json.data)
    .catch(this.handleError);
}

updateHero(hero: Hero): Promise<Hero> {
  const url = `${this.heroesUrl}/${hero.id}`
  return this.http.put(url, JSON.stingify(hero), {header: this.headers})
    .toPromise()
    .then(() => hero)
    .catch(this.handleError);
}

removeHero(id: number): Promise<void> {
  let url = `${this.heroUrl}/${id}`;
  return this.http.delete(url, {headers: this.headers})
    .toPromise()
    .then(() => null)
    .catch(this.handleError);
}
Donate - Support to make this site better.
捐助 - 支持我让我做得更好.