基本设置

模拟 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);
  }
}