英雄案例笔记--httpClient

内存 Web API:

npm install angular-in-memory-web-api --save

HttpClientInMemoryWebApiModule.forRoot(
      InMemoryDataService, { dataEncapsulation: false }
    )

在英雄指南范例中创建一个类 src/app/in-memory-data.service.ts,内容如下:

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

export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const 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};
  }
}

这个文件替代了 mock-heroes.ts(你可以安全删除它了)。

等你真实的服务器就绪时,就可以删除这个内存 Web API,该应用的请求就会直接发给真实的服务器。

import { HttpClient, HttpHeaders } from '@angular/common/http';
private heroesUrl = 'api/heroes';  
constructor(
  private http: HttpClient,
  private messageService: MessageService) { }
/*  getHeroes(): Observable<Hero[]> { /!*使用 RxJS 的 of() 函数来把模拟英雄数据返回为 Observable<Hero[]> 格式*!/
    this.messageService.add('HeroService: fetched heroes');
    return of(HEROES);
  }*/
  getHeroes (): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl);
  }

其它 API 可能在返回对象中深埋着你想要的数据。 你可能要借助 RxJS 的 map 操作符对 Observable 的结果进行处理,以便把这些数据挖掘出来。
错误处理:
凡事皆会出错,要捕获错误,你就要使用 RxJS 的 catchError() 操作符来建立对 Observable 结果的处理管道(pipe)。

import { catchError, map, tap } from 'rxjs/operators';
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第一节:初识Angular-CLI第二节:登录组件的构建第三节:建立一个待办事项应用第四节:进化!模块化你的应用第...
    接灰的电子产品阅读 15,705评论 31 77
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,508评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,704评论 25 709
  • 靖难之役,成祖靠着宦官党羽杀出一条血路。继位后,委派宦官担任要职。自此以后,再无人敢公然取笑我们,区区阉人,从此在...
    沈流光9749阅读 3,424评论 0 2
  • 最近感悟:先相信而后看见。 12月下旬欢喜在知识星球上线【一块输出1000张卡片】,规则很简单,如图: 加入的战友...
    员子圆梦阅读 1,345评论 0 0