Angular学习问题笔记 (2020.6.17)
ContentChild 装饰器
import { AfterContentInit, ContentChild, Directive } from '@angular/core'; @Directive({selector: 'child-directive'}) class ChildDirective { } @Directive({selector: 'someDir'}) class SomeDir implements AfterContentInit { @ContentChild(ChildDirective) contentChild!: ChildDirective; ngAfterContentInit() { // contentChild is set } }
BehaviorSubject
AfterContentInit AfterViewInit区别
AfterContentInit
interface AfterContentInit { ngAfterContentInit(): void }
AfterViewInit
参考:https://angular.cn/api/core/AfterViewInit
一个生命周期钩子,会在Angular完全初始化了组件的视图后调用。定义一个ngAfterViewInit()方法来处理一些额外的初始化任务。
ContentChild ViewChild
Renderer2 基类
NgZone,onStable
class NgZone { static isInAngularZone(): boolean static assertInAngularZone(): void static assertNotInAngularZone(): void constructor(__0) hasPendingMacrotasks: boolean hasPendingMicrotasks: boolean isStable: boolean onUnstable: EventEmitter<any> onMicrotaskEmpty: EventEmitter<any> onStable: EventEmitter<any> onError: EventEmitter<any> run runTask runGuarded runOutsideAngular }
onStable
当最后一个onMicrotaskEmpty运行并且不再有微任务时通知,这意味着我们将放弃VM轮。此事件只被调用一次。
示例代码:
private contentChildrenChanges$: Observable<null> = defer(() => { if (this.nzListItemActions) { return of(null) } return this.ngZone.onStable.asObservable().pipe( take(1), switchMap(() => this.contentChildrenChanges$) ) })
QueryList
TemplateRef和ElementRef
ViewChild和ViewChildren
Subject 主体
abstract class ChangeDetectorRef { abstract markForCheck(): void abstract detach(): void abstract detectChanges(): void abstract checkNoChanges(): void abstract reattach(): void }
子类 ViewRef
方法:
detectChanges() 检查该视图及其子视图。与detach结合使用可以实现局部变更检测。
abstract detectChanges(): void
asObservable() 查不到资料
defer()
defer(() => Observable.of(a, b, c))
switchMap
take takeUntil 过滤操作符
take
示例:获取时间间隔为1秒的interval Observable的最初5秒
var interval = Rx.Observable.interval(1000); var five = interval.take(5); five.subscribe(x => console.log(x));
takeUntil
参考:https://cn.rx.js.org/class/es6/Observable.js~Observable.html#instance-method-takeUntil
发出源Observable发出的值,直到notifier Observable发出值。
它发出源Observable的值,然后直到第二个Observable(即notifier)发出项,它便完成。
takeUntil订阅并开始镜像源Observable,它还监视另外一个Observable,即你提供的notifier.如果notifier发出值或complete通知,那么输出Observable停止镜像源Observable,然后完成。
示例:每秒都发出值,知道第一次点击发生
var interval = Rx.Observable.interval(1000); var clicks = Rx.Observable.fromEvent(document, 'click'); var result = interval.takeUntil(clicks); result.subscribe(x => console.log(x));
merge() 和 mergeAll() 组合操作符
merge()
mergeAll()
参考:https://cn.rx.js.org/class/es6/Observable.js~Observable.html#instance-method-mergeAll
将高阶Observable转换成一阶Observable,一阶Observable会同时发出在内部Observables上发出的所有制
abstract
exportAs
@Directive({ selector: 'child-dir', exportAs: 'child' }) class ChildDir { } @Component({ selector: 'main', template: `<child-dir #c="child"></child-dir>` }) class MainComponent { }