2017-02-10 49 views
1

我目前正在開發Angular 2入門教程。我在last chapter called "HTTP"。我剛剛學會了如何將數據集添加到集合列表中。它基本上展示瞭如何將POST事件放入後端API。Angular 2入門教程神奇地生成數據

我創建了一個模擬的服務來模擬真實的HTTP後臺:

import { InMemoryDbService } from 'angular-in-memory-web-api'; 

export class InMemoryDataService implements InMemoryDbService { 
    createDb() { 
    let heroes = [ 
     {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'} 
    ]; 
    return { heroes }; 
    } 
} 

也有是與此數據撥弄服務:

import {Injectable} from "@angular/core"; 
import {Http, Headers} from "@angular/http"; 
import "rxjs/add/operator/toPromise"; 
import {Hero} from "./hero"; 

@Injectable() 
export class HeroService { 

    private heroesUrl = 'api/heroes'; // URL to web api 
    private headers = new Headers({'Content-Type': 'application/json'}); 

    constructor(private http: Http) { 

    } 

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

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

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

    getHero(id: number): Promise<Hero> { 
    const url = `${this.heroesUrl}/${id}`; 
    return this.http.get(url) 
     .toPromise() 
     .then(response => response.json().data as Hero) 
     .catch(this.handleError); 
    } 

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

add方法是由所謂的UI按鈕的點擊監聽器如下所示:

add(name: string): void { 
    name = name.trim(); 
    if (!name) { return; } 
    this.heroService.create(name).then(hero => { this.heroes.push(hero); this.selectedHero = null;}); 
    } 

您可以輕鬆地播放與此應用程序的類似狀態周圍here

你在輸入框中添加一些東西,然後點擊「保存」。點擊監聽器調用「add()」並添加服務的「create()」,最後調用web服務。新創建的數據集被添加到列表中,實際上是模擬數據的一部分。它以給定名稱(源自輸入網絡組件)和用「id」存儲的撥號號碼(如果最後一個英雄是20,你得到21)存儲。

此代碼讓我感到非常困惑。我無法理解它的工作原理。爲什麼這個模擬API現在該怎麼做,只是因爲它得到了一個名字?我的意思是你東西給API提供一個名稱。精細。但是如何在世界上知道還有另一個需要自動遞增的屬性「id」?

只是爲了顯示它從另一個樣板隔離,這是代碼片段我說的是:

http.post('api/heroes', JSON.stringify({name: name}), new Headers({Content-Type: 'application/json'}); 
+0

好,因爲它的這種方式來實現:當接收到一個新的名字,它找到的最大ID,增加它,並增加了新的英雄的名單。請參閱https://github.com/angular/in-memory-web-api/blob/master/in-memory-backend.service.js#L494和https://github.com/angular/in-memory-web -api/blob/master/in-memory-backend.service.js#L382 –

+0

@JBNizet噢,以及...:D – OddDev

+0

@JBNizet這意味着如果我使用模擬服務並擁有一個名爲id的屬性,所有事情都由InMemoryDbService完成已經?我只需要爲其他屬性提供適當的值,不是嗎?如果我從頭開始沒有任何數據,或者我的數據沒有「id」屬性,這也是真的嗎? – OddDev

回答

0

的魔力來自使用app.module

InMemoryWebApiModule.forRoot(InMemoryDataService, {delay: 200})

如果您鑽取模塊,它將返回一個XHRBackend,它將您正在創建的xhr請求傳遞給內存數據庫。

export declare function inMemoryBackendServiceFactory(injector: Injector, dbService: InMemoryDbService, options: InMemoryBackendConfig): XHRBackend;