1

我正在构建一个类来扩展我所有的组件来监听像这样的调整事件

@HostListener( 'window:resize', ['$event'] ).....//function

在其他组件中,我监听相同的事件,当类扩展时,这会导致一个事件覆盖另一个事件,因此只有一个在窗口大小发生变化时触发。我发现这是问题所在,因为我有一门大课,我不评论要在一个地方修补所有东西。当我将此添加到课程中时

@HostListener( 'window:resize', ['$event'] ) reSize( event ){ this.calcScreen(); }
@HostListener( 'window:resize', ['$event'] ) reScale( event ){ this.checkScrn(); }

我收到一个错误,指出存在重复,这解释了为什么它们在扩展时会相互覆盖。我给这些函数起不同的名字,看看是否有帮助,我认为第二个是占主导地位的函数。@HostListener但是最后只有一个

reSize( event ){ this.calcScreen(); this.checkScrn(); }

它们都按需要运行。

我该如何解决这个问题?到目前为止,这是我的课程。

AppComponent

export class AppComponent extends GridFactory implements OnInit {
    MainFrame: SiteFrame;

    @HostListener( 'window:resize', ['$event'] ) onResize( event ){ this.calcScreen(); }

    constructor( @Self() public appSpecs: ElementRef ){
        super( appSpecs );
    }

    ngOnInit(){ this.calcScreen(); }

    calcScreen(){ this.MainFrame = uiMonitor(); }
}

GridFactory

export class GridFactory implements AfterViewInit {
    ScreenCore   : ScrnCore  = new ScrnCore();
    GridSettings : GridSpecs = new GridSpecs();

    @HostListener( 'window:resize', ['$event'] ) onResize( event ){ this.checkScrn(); }


    constructor( @Self() public appSpecs: ElementRef ){}

    ngAfterViewInit(){ this.checkScrn(); }

    checkScrn(){
        this.ScreenCore.Width   = this.appSpecs.nativeElement.offsetWidth;
        this.ScreenCore.Height  = this.appSpecs.nativeElement.offsetHeight;

        this.activteGrid( this.ScreenCore );
    }

    activteGrid( data: ScrnCore ){ this.GridSettings = gridManager( data.Width ); }
}

AppComponent (both combined as one class)

export class AppComponent implements OnInit, AfterViewInit{
    MainFrame    : SiteFrame = new SiteFrame();
    ScreenCore   : ScrnCore  = new ScrnCore();
    GridSettings : GridSpecs = new GridSpecs();

    @HostListener('window:resize', ['$event'])
    reSize(event){ this.calcScreen(); this.checkScrn(); }

    constructor( @Self() public appSpecs: ElementRef ){}

    ngOnInit(){ this.calcScreen(); }

    ngAfterViewInit(){ this.checkScrn(); }

    calcScreen(){ this.MainFrame = uiMonitor(); }

    checkScrn(){
        this.ScreenCore.Width   = this.appSpecs.nativeElement.offsetWidth;
        this.ScreenCore.Height  = this.appSpecs.nativeElement.offsetHeight;

        this.activteGrid( this.ScreenCore );
    }

    activteGrid( data: ScrnCore ){ this.GridSettings = gridManager( data.Width ); }
}
4

2 回答 2

0

您可以使用super前缀从扩展类中调用方法。

所以你的 app 方法应该是这样的:

@HostListener('window:resize', ['$event'])
reSize(event){ this.calcScreen(); super.onResize(event); }

这种方法避免了代码冗余。

于 2019-03-14T12:02:21.797 回答
0

原来我所要做的就是把它像这样留在AppComponent

@HostListener('window:resize', ['$event'])
reSize(event){ this.calcScreen(); this.checkScrn(); }

即使我没有在 AppComponent 上定义它,它仍然会注册,因为我正在扩展GridFactory它,我本能地认为这不起作用......但它确实如此:)

于 2017-11-18T01:36:02.510 回答