Angular 安格拉尔2:主持人是否应该取消订阅?主机Listner是如何工作的?如果我不需要退订,什么时候可以退订?
我一直在听许多组件中的滚动事件。我并没有退订。这会引起问题吗 是否应该取消主机侦听器的订阅 不,不需要取消订阅-当主机侦听器所属的组件被销毁时,主机侦听器将被销毁 主机Listner[sic]是如何工作的 为了更好地理解HostListener的工作原理,我建议阅读这些有用的文档Angular 安格拉尔2:主持人是否应该取消订阅?主机Listner是如何工作的?如果我不需要退订,什么时候可以退订?,angular,events,unsubscribe,Angular,Events,Unsubscribe,我一直在听许多组件中的滚动事件。我并没有退订。这会引起问题吗 是否应该取消主机侦听器的订阅 不,不需要取消订阅-当主机侦听器所属的组件被销毁时,主机侦听器将被销毁 主机Listner[sic]是如何工作的 为了更好地理解HostListener的工作原理,我建议阅读这些有用的文档 什么时候取消订阅 当父组件/指令被销毁时 为了说明我的观点,请看以下示例应用程序: app.module.ts @HostListener('window:scroll', ['$event']) o
为了说明我的观点,请看以下示例应用程序: app.module.ts
@HostListener('window:scroll', ['$event'])
onScroll(event) {
// Do something
}
app.component.html
import { RouterModule, Routes } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { Test1Component } from './test1/test1.component';
import { Test2Component } from './test2/test2.component';
const routes: Routes = [
{ path: 'test1', component: Test1Component },
{ path: 'test2', component: Test2Component },
{ path: '**', redirectTo: 'test1' }
];
@NgModule({
declarations: [
AppComponent,
Test1Component,
Test2Component
],
imports: [
BrowserModule,
RouterModule.forRoot(routes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
test2.component.ts
<h1>host listener example</h1>
<a routerLink="test1">test1</a>
<a routerLink="test2">test2</a>
<router-outlet></router-outlet>
<div>
<p>some content</p>
<div style="height:1000px"></div>
<p>some content down the page</p>
</div>
import { Component, OnInit, HostListener } from '@angular/core';
@Component({
selector: 'app-test1',
templateUrl: './test1.component.html',
styleUrls: ['./test1.component.css']
})
export class Test1Component implements OnInit {
constructor() { }
ngOnInit() { }
@HostListener('window:scroll', ['$event'])
onScroll(event) {
console.log('scroll event in Test1Component', event);
}
}
应用程序将默认重定向到主机:port/test1,呈现TestComponent1。当滚动事件发生时,它将记录到控制台“Test1Component中的滚动事件”和有关该事件的信息。如果将url更改为host:port/test2,它将销毁Test1组件(及其@HostListeners)并呈现test2组件。现在,当一个scroll事件发生时,它将记录到控制台“Test2Component中的scroll事件”和关于该事件的信息。请注意它是如何不记录“Test1Component中的滚动事件”的,因为@HostListener在其父组件(Test1Component)被销毁时被销毁。否,不需要取消订阅,因为您没有订阅
import { Component, OnInit, HostListener } from '@angular/core';
@Component({
selector: 'app-test2',
templateUrl: './test2.component.html',
styleUrls: ['./test2.component.css']
})
export class Test2Component implements OnInit {
constructor() { }
ngOnInit() {
}
@HostListener('window:scroll', ['$event'])
onScroll(event) {
console.log('scroll event in Test2Component', event);
}
}