文章内容

2020/5/14 18:31:48,作 者: 黄兵

使用Angular in-memory-web-api 无任何数据

最近在参照这篇文章,使用in-memory-web-api,模拟获取后端数据,但是怎么也获取不到数据,具体NgModel代码如下:

  imports: [
    BrowserModule,
    SharedModule,
    BrowserAnimationsModule,
    InMemoryWebApiModule.forRoot(InMemoryDataService),
    AppRoutingModule,
    RouterModule,
    A11yModule,
    ClipboardModule
  ],

已经增加了数据,具体示例代码在此处:db.ts

编写服务,具体代码在此处:hero.ts

但是请求无任何数据。

对比了一下官方文档和自己的代码,原来是请求地址有问题,经过修改之后,代码如下:

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';

@Injectable()
export class GetPhoneNumberListService {
  // private headers = new Headers({ 'Content-Type': 'application/json' });
  private phoneNumberListUrl = 'api/phoneNumberList';  // URL to web api
  constructor(private http: HttpClient) {
  }

  getPhoneNumber(): Observable {
    return this.http.get(this.phoneNumberListUrl, {
      headers: new HttpHeaders().set('Content-Type', 'application/json'),
    }).pipe(map((response: Response) => {
      return response;
    }), catchError((error: any) => {
      return throwError(error);
    }));
  }
}

这里主要是phoneNumberListUrl这里的url,需要与模型的名称相对应,下面是节选部分代码:

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

export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const phoneNumberList = [
      {
        phone_number: '4433908875',
        area_code: '+1',
        country_flag: 'https://pdflib-1253677444.cos.ap-beijing-1.myqcloud.com/sms_resouce/static/images/sms_america/america_flag_344x194dp.png',
        last_time: '2020/5/14 15:19',
        sms_count: '1000',
        create_time: '2020/5/14 15:19',
        state: 'live',
        state_img: 'https://pdflib-1253677444.cos.ap-beijing-1.myqcloud.com/sms_resouce/static/images/sms_america/done_40dp.png'
      },

主要与const phoneNumberList对应,否则无任何数据,也不会报404错误。


参考资料:

1、https://stackblitz.com/edit/angular-feature-modules-example?embed=1&file=app%2Fapp.module.ts&view=editor

2、Angular in-memory-web-api

3、Mocking with Angular: More than just unit testing


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - 使用Angular in-memory-web-api 无任何数据

WebStorm .http文件详解
json理解
分享到:

发表评论

评论列表