美文网首页
英雄案例笔记--httpClient

英雄案例笔记--httpClient

作者: Monee121 | 来源:发表于2018-03-11 15:18 被阅读0次

内存 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';

相关文章

网友评论

      本文标题:英雄案例笔记--httpClient

      本文链接:https://www.haomeiwen.com/subject/hxdbfftx.html