angular之HttpClient

81 阅读1分钟

初步认识,

  • XMLHttpRequest和RxJs结合封装的。
  • 当在组件中有异步相关操作的时候,组件销毁时。该异步操作依然会在执行
    • 组件被销毁,但是还有相关异步在操作组件中视图(组件模板、指令相关操作)。导致报错: Uncaught (in promise): Error: NG0911: View has already been destroyed.
    • 那时候就需要在组件销毁的时候清除异步操作(不限制于http请求,setTimeout等异步操作)
    • 由于HttpClient基于rxjs封装的,所以在组件的destroy钩子中使用rxjs清除对应的请求
    import { ElementRef, OnInit, ViewChild, OnDestroy } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Subscription } from 'rxjs';
    // `takeUntil`RxJS中常用操作符
    // `takeUntil`调用`next()`和`complete()`来发送信号取消订阅、通知Subject已完成
    import { takeUntil } from 'rxjs/operators';
    @ViewChild('tagInput', { static: true }) tagInput!: ElementRef<HTMLInputElement>;
    export class ProAccountCenterComponent implements OnInit, OnDestroy {
        private httpSubscription: Subscription = new Subscription();
        private ngUnsubscribe: Subject<void> = new Subject<void>();
        constructor(private http: HttpClient) {}
        ngOnInit(): void {
            this.httpSubscription = this.http.get('https://api.example.com/list')
            .subscribe(res => {
                // 更新视图
                this.tagInput.value = res
            });
            this.loadViewByData()
        }
        ngOnDestroy(){
            // 取消https://api.example.com/data
            this.ngUnsubscribe.next()
            this.ngUnsubscribe.complete()
            // 取消https://api.example.com/list
            this.httpSubscription.unsubscribe()
        }
        async loadViewByData(){
            const res = await firstValueForm(
                this.http.get('https://api.example.com/data')
                .pipe(takeUntil(this.ngUnsubscribe))
            )
            this.tagInput.value = res
        }
    }