我应该何时存储Subscription
实例并unsubscribe()
在NgOnDestroy生命周期中调用,何时可以忽略它们?
保存所有订阅会在组件代码中引入很多混乱.
HTTP客户端指南忽略这样的订阅:
getHeroes() {
this.heroService.getHeroes()
.subscribe(
heroes => this.heroes = heroes,
error => this.errorMessage = <any>error);
}
Run Code Online (Sandbox Code Playgroud)
同时," 航线与导航指南"说:
最终,我们会在其他地方导航.路由器将从DOM中删除此组件并将其销毁.在此之前我们需要自己清理.具体来说,我们必须在Angular破坏组件之前取消订阅.如果不这样做可能会造成内存泄漏.
我们取消订阅我们
Observable
的ngOnDestroy
方法.
private sub: any;
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = +params['id']; // (+) converts string 'id' to a number
this.service.getHero(id).then(hero => this.hero = hero);
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud) subscription observable rxjs angular angular-component-life-cycle
我经常遇到这个问题。我有一个如图所示的元素
<div class="element-1" *ngIf="isShown"></div>
Run Code Online (Sandbox Code Playgroud)
默认, isShown = false;
点击一个元素,我正在 isShown = true;
现在,在相同的点击回调函数,如果我试图让element-1
作为
$('.element-1')
,我没有得到该元素,因为当该元素可能不会立即在DOM中出现isShown = true
。
我可以使用得到相同的ngAfterContentChecked
。但是ngAfterContentChecked
打了很多遍。
因此,如何不使用元素ngAfterContentChecked
呢?
这是我的要素
<app-card-kpi-inline-overlay #kpisOverlay class="child-component all-kpis-overlay-wrap {{selectedView}}" [style.left.px]="kpiLeft" *ngIf="data['openKpiDetails']==true" [cardData]="data"></app-card-kpi-inline-overlay>
Run Code Online (Sandbox Code Playgroud)
这是我的ts方法代码
@ViewChild('kpisOverlay') kpisOverlay: ElementRef;
showKpiSection(i, event, card) {
card['openKpiDetails'] = !card['openKpiDetails'];
event.stopPropagation();
if (card['openKpiDetails']) {
setTimeout(() => {
const el: HTMLElement = this.kpisOverlay.nativeElement;
console.log(el); // always showing undefined
}, 0);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试切换标志。但是控制台始终在打印undefined
。
以下是我的切换元素
<div (click)="showKpiSection(i, $event, data)">Get element</div>
Run Code Online (Sandbox Code Playgroud) 我在看问题:https : //stackoverflow.com/a/44737636/973651
我有一个带有ngIf
条件的 div ,我想div
在渲染时捕获一个事件。据说,您可以使用该AfterContentInit
事件。我上面引用的文章显示了一个示例,我已经复制了该示例,但没有成功使其正常工作。
我不知道我做错了什么,但我无法让它发挥作用。我没有收到任何错误,但它对我不起作用。
我的指令定义为:
import { AfterContentInit, EventEmitter, Output, Directive } from '@angular/core';
@Directive({ selector: '[after-if]' })
export class AfterIfDirective implements AfterContentInit {
@Output('after-if')
public after: EventEmitter<AfterIfDirective> = new EventEmitter();
public ngAfterContentInit(): void {
debugger;
setTimeout(() => {
// timeout helps prevent unexpected change errors
this.after.next(this);
});
}
}
Run Code Online (Sandbox Code Playgroud)
在我的页面组件中导入。
import { AfterIfDirective } from '../directives/after-if';
@NgModule({
providers: [],
imports: [NgModel, BrowserAnimationsModule, HttpClientModule,
AfterIfDirective],
exports: [NgModel, BrowserAnimationsModule, AfterIfDirective]
}) …
Run Code Online (Sandbox Code Playgroud)