LoginSignup
21
9

More than 5 years have passed since last update.

Angular2 angular-in-memory-web-api で モック と urlアクセスを共存させる方法

Last updated at Posted at 2017-04-07

angular-in-memory-web-api とは

WebAPI からのデータ取得部分のモックです。
Angular2 で提供されています。
Angular 公式の TUTORIAL に出てきます。
https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

ざっくり使い方

  • import
app.module.ts
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService }  from './in-memory-data.service';

@NgModule({
    imports: [
        InMemoryWebApiModule.forRoot(InMemoryDataService),
    ],
})
  • モックデータは変数にjsonを設定。その変数をpathと紐づける形で定義します。
in-memory-data.service.ts
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
    createDb() {
        let timesheets = [{  },{  }];

        return {'timesheets':timesheets};
    }
}
  • request 部分のコードは実際WebAPIへアクセスする時の形で記述します。但し、urlはangular-in-memory-web-api 用のpathを指定する必要があります。
timesheets.service.ts
export class TimesheetsService {
    private timesheetsUrl = 'api/timesheets';  // URL to web api

    constructor(private http: Http) { }

    getTimesheets(): Promise<Timesheets[]> {
        return this.http.get(this.timesheetsUrl)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }
}

問題

一部のAPIについてのみ実際のurlアクセスを行いたい場合に、urlを変更するだけでは 404 - Not Found となってしまった。

解決方法

Config を設定する必要があります。
passThruUnknownUrl:true を指定します。

app.module.ts
@NgModule({
    imports: [
        InMemoryWebApiModule.forRoot(InMemoryDataService, { passThruUnknownUrl: true }),
    ],
})


日本語で言及している記述が見つけられなかったので書いてみました。

21
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
9