Angular 7窗口大小调整事件未在服务中运行
我有一个带有ReplaySubject变量的服务,我想在组件中使用它,我的理解是它应该可以工作,但是WindowResize事件根本不会触发Angular 7窗口大小调整事件未在服务中运行,angular,typescript,Angular,Typescript,我有一个带有ReplaySubject变量的服务,我想在组件中使用它,我的理解是它应该可以工作,但是WindowResize事件根本不会触发 import { Injectable, HostListener } from '@angular/core'; import { ReplaySubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class WindowResizeService {
import { Injectable, HostListener } from '@angular/core';
import { ReplaySubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class WindowResizeService {
windowWidth;
constructor() {
console.log("Window resize service active");
this.windowWidth = new ReplaySubject(1);
}
@HostListener('window:resize', ['$event'])
onResize(event) {
console.log("Width: " + event.target.innerWidth);
this.windowWidth.next(event.target.innerWidth);
}
}
在组件中,我以以下方式订阅:
import { WindowResizeService } from './window-resize-service';
constructor(private windowResize: WindowResizeService) implements OnInit {
}
ngOnInit() {
this.windowResize.windowWidth.subscribe(
(value) => { console.log(value) }
);
}
因此,我激活了
窗口调整服务大小
事件,但服务或组件中的控制台.log
没有运行。感谢您的帮助:)AHostListener
就是它所说的。它侦听主机组件上的事件。您可以为全局侦听器使用额外的窗口
、文档
或正文
绑定,这一便利性并不会使HostListener在服务内部工作
为此,您必须使用渲染器
、简单的窗口。addEventListener
或rxjsfromEvent(窗口)
另一种方法是,将
@HostListener()
添加到AppComponent(并且仅在那里),并让它从那里发出可观察到的服务。干杯,这是我问过之后想的,我打算将其添加为窗口。addEventListener
,但是在AppComponent中使用它听起来更干净。计时器启动后,将在5分钟内将您的答案标记为正确。