1 从服务中调用HTTP数据, 导入服务
src/app/hero.service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
constructor(
private http: HttpClient,
private messageService: MessageService) { }
/** Log a HeroService message with the MessageService */
private log(message: string) {
this.messageService.add(`HeroService: ${message}`);
}
private heroesUrl = 'api/heroes'; // URL to web api
2 通过 HttpClient 获取英雄, 实际上只是将返回的方法修改成从 this.http.get<Hero[]>(this.heroesUrl)
, 通过模拟的api请求数据
src/app/hero.service.ts
/** GET heroes from the server */
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
}
3 错误处理
src/app/hero.service.ts
import { catchError, map, tap } from 'rxjs/operators';
- 3.2 使用RXJS的结果管道
pipe()
方法来扩展 Observable
的结果,并给它一个 catchError()
操作符, 意思是当执行完成时管道启动, 如果有错误时将会调用错误处理的方法
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
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);
};
}
- 3.4 监听获取数据事件, 通过RXJS的 tap操作符, 该操作符会查看 Observable 中的值,使用那些值做一些事情,并且把它们传出来。 这种 tap() 回调不会改变这些值本身。这里只是记录日志,并没有使用其中的值.
/** GET heroes from the server */
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}