今天完成的事情:
Angular9 可观察对象用法
Angular 使用可观察对象作为处理各种常用异步操作的接口:
EventEmitter 类派生自 Observable
HTTP 模块使用可观察对象来处理 AJAX 请求和响应
路由器和表单模块使用可观察对象来监听对用户输入事件的响应
在组件之间传递数据
@Component({
selector: 'zippy',
template: `
<div class="zippy">
<div (click)="toggle()">Toggle</div>
<div [hidden]="!visible">
<ng-content></ng-content>
</div>
</div>`})
export class ZippyComponent {
visible = true;
@Output() open = new EventEmitter<any>();
@Output() close = new EventEmitter<any>();
toggle() {
this.visible = !this.visible;
if (this.visible) {
this.open.emit(null);
} else {
this.close.emit(null);
}
}
}
路由器 (router)
import { Router, NavigationStart } from '@angular/router';
import { filter } from 'rxjs/operators';
@Component({
selector: 'app-routable',
templateUrl: './routable.component.html',
styleUrls: ['./routable.component.css']
})
export class Routable1Component implements OnInit {
navStart: Observable<NavigationStart>;
constructor(private router: Router) {
// Create a new Observable that publishes only the NavigationStart event
this.navStart = router.events.pipe(
filter(evt => evt instanceof NavigationStart)
) as Observable<NavigationStart>;
}
ngOnInit() {
this.navStart.subscribe(evt => console.log('Navigation Started!'));
}
}
HTTP服务:
错误处理:
使用 RxJS 的 catchError() 操作符来建立对 Observable 结果的处理管道(pipe)
在hero.service.ts中添加
import { catchError, map, tap } from 'rxjs/operators';
使用pipe() 方法来扩展 Observable 的结果
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}
对这个错误处理函数进行配置
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
this.log(`${operation} failed: ${error.message}`);
return of(result as T);
};
}
窥探 Observable
修改getHeroes()
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}
通过 id 获取英雄
修改getHero(id: number)
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}`))
);
}
问题:
处理错误和获取数据出问题,不会解决
评论