基本設定
模擬 data.ts
建立模擬 api 資料
export class MockData {
`createDb()` {
let mock = [
{ id: '1', name: 'Object A' },
{ id: '2', name: 'Object B' },
{ id: '3', name: 'Object C' },
{ id: '4', name: 'Object D' }
];
return {mock};
}
}
main.ts
讓依賴注入器為 XHRBackend 請求提供 InMemoryBackendService。另外,提供一個包含 a 的類
createDb()
函式(在本例中為 MockData)指定 SEED_DATA 請求的模擬 API 路由。
import { XHRBackend, HTTP_PROVIDERS } from '@angular/http';
import { InMemoryBackendService, SEED_DATA } from 'angular2-in-memory-web-api';
import { MockData } from './mock-data';
import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [
HTTP_PROVIDERS,
{ provide: XHRBackend, useClass: InMemoryBackendService },
{ provide: SEED_DATA, useClass: MockData }
]);
mock.service.ts
為建立的 API 路由呼叫 get 請求的示例
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Mock } from './mock';
@`Injectable()`
export class MockService {
// URL to web api
private mockUrl = 'app/mock';
constructor (private http: Http) {}
`getData()`: Promise<Mock[]> {
return `this.http.get(this.mockUrl)`
`.toPromise()`
`.then(this.extractData)`
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Promise.reject(errMsg);
}
}