Angular--模拟数据服务器

HttpClient

模拟数据服务器

内存Web API(In-momory Web API),通过HttpClient发起请求和接收响应

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

 导入 HttpClientInMemoryWebApiModuleInMemoryDataService

import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService }  from './in-memory-data.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
把 HttpClient 注入到构造函数中一个名叫 http 的私有属性中。

      

constructor(
  private http: HttpClient,
  private messageService: MessageService) { }

private log(message: string) {
  this.messageService.add('HeroService: ' + message);
}

private heroesUrl = 'api/heroes';  // URL to web api

HttpClient.get 返回响应数据

响应体当做无类型的 JSON 对象进行返回,借助 RxJS 的 map 操作符对 Observable 的结果进行处理,以便把这些数据挖掘出来。

错误处理

使用 RxJS 的 catchError() 操作符来建立对 Observable 结果的处理管道(pipe)

import { catchError, map, tap } from 'rxjs/operators';

getHeroes (): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      catchError(this.handleError('getHeroes', []))
    );
}

catchError() 操作符会拦截失败的 Observable。 它把错误对象传给错误处理器错误处理器会处理这个错误。

handleError返回给 catchError 返回一个错误处理函数,

操作名、出错时要返回的安全值
private handleError<T> (operation = 'operation', result?: T) {
  return (error: any): Observable<T> => {
 
    // TODO: send the error to remote logging infrastructure
    console.error(error); // log to console instead
 
    // TODO: better job of transforming error for user consumption
    this.log(`${operation} failed: ${error.message}`);
 
    // Let the app keep running by returning an empty result.
    return of(result as T);
  };
}

窥探 Observable 的数据流,并通过 log() 函数往页面底部发送一条消息。

tap 操作符查看 Observable 中的值

通过 id 获取

通过 api/hero/:id 的形式根据 id 获取单个对象,如果id查找不到,出现404

getHero(id: number): Observable<Hero> {
  const url = `${this.heroesUrl}/${id}`;
   return this.http.get<Hero>(url).pipe(
    tap(_ => this.log(`fetched hero id=${id}`)),
    catchError(this.handleError<Hero>(`getHero id=${id}`))
  );
}

修改

添加保存按钮,绑定click时间,事件绑定会调用组件中一个名叫 save() 的新方法:

<button (click)="save()">save</button>

使用updateHero() 方法保存修改,返回前一个视图,会使用 http.put()将修改

src/app/hero-detail/hero-detail.component.ts (save)

      

save(): void {
   this.heroService.updateHero(this.hero)
     .subscribe(() => this.goBack());
 }

 

 

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值