Guide on how to use window.resize subscription in an Angular service?

I have been experimenting with the WindowService in my Angular project. Here is the code I have written:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

interface WindowSize {
  width?: number;
  height?: number;
}

@Injectable({
  providedIn: 'root'
})
export class WindowService {
  webWindow = window;
  windowHeight: number;
  windowWidth: number;
  windowSize: number;
  constructor() {

    this.getWindowSize = this.getWindowSize.bind(this);

  }


  getWindowSize(): Observable<any> {
    return this.webWindow.addEventListener('resize', ()=> {
      this.windowSize = {
        width: window.innerWidth,
        height: window.innerHeight
      };
      return this.windowSize;
    });
  }
}

In one of my components, I am trying to subscribe to the getWindowSize method:

  ngOnInit() {
    this.loadUser();
    this.windowSize = this.windowService.getWindowSize().subscribe(data=> {
      console.log(data)
      this.windowSize = data;
    }); 
  }

The error message I am encountering is as follows:

AppComponent.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'subscribe' of undefined at FeedlistComponent.ngOnInit

Answer №1

Check out this amazing solution that ensures no errors in the server-side environment and prevents subscription leaks:

import {DOCUMENT} from '@angular/common';
import {Inject, Injectable} from '@angular/core';
import {fromEvent, NEVER, Observable} from 'rxjs';

// @dynamic
@Injectable({
    providedIn: 'root',
})
export class ResizeHandler extends Observable<Event> {
    private readonly resize$: Observable<Event>;

    constructor(
        @Inject(DOCUMENT) {defaultView}: Document,
    ) {
        super(subscriber => this.resize$.subscribe(subscriber));

        this.resize$ = defaultView ? fromEvent(defaultView, 'resize') : NEVER;
    }
}

Note: Make sure to include the comment // @dynamic to avoid AOT build failures with Document type as a constructor argument.

Note: It's recommended to implement event throttling for better performance.

Implementation example:

export class MyComponent {
    constructor(@Inject(ResizeHandler) resize$: Observable<Event>) {
        resize$.subscribe(console.log);
    }
}

Answer №2

Adding an event listener does not result in an observable being returned. An alternative approach is to utilize fromEvent(window, 'resize'). You can find more information about the fromEvent method here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adding a mat-error to a mat-input-field on-the-fly

To handle user input exceeding maxLength and dynamically add < mat-error > to the DOM in case of an error, I have implemented an attribute directive that enforces the character limit on input fields. This directive is used across multiple files in the proj ...

Prevent repetition of errors during compiling in the ahead-of-time (AOT

I need assistance with optimizing my codebase in Angular 2 using angular-cli. When I run the command "ng build --prod", I encounter an error that is preventing the output of the dist folder. This error claims that there is a duplicate identifier in one of ...

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...

Tips for implementing a guard feature using a modal window

I am looking to implement a dialog window with yes and no responses when clicking on a router link. If the user selects 'yes', I want to pass through the canActivate guard. The issue arises when returning to the same router with the guard in pla ...

What is the best way to reset a dropdown list value in angular?

Is there a way to erase the selected value from an Angular dropdown list using either an x button or a clear button? Thank you. Code <div fxFlex fxLayout="row" formGroupName="people"> <mat-form-field appearance=&quo ...

Angular routes can cause object attributes to become undefined

I am new to Angular and struggling with an issue. Despite reading numerous similar questions and answers related to AJAX, async programming, my problem remains unsolved. When I click on the 'Details' button to view product details, the routing wo ...

Tips for updating the icon based on the active or inactive status in ag-grid within an angular application

HTML* <ng-template #actionButtons let-data="data"> <div class="cell-actions"> <a href="javascript:;" (click)="assign()"> <i nz-icon nzType="user-add" nzTheme= ...

The data in my MySQL table is not appearing on an Angular Material table when using Node.js

HTML file content <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <ng-container matColumnDef="id"> <th mat-header-cell *matHeaderCellDef> No. </th> <td mat-cell *matCellDef="let element"> {{ele ...

Discover the Hassle-Free Approach to Triggering Angular Material Menu with ViewChild and MatMenuTrigger

Is there a way to programmatically open an Angular Material menu using a Template Reference Variable on a button trigger that is accessed in the component through ViewChild? I want the menu to open when the mouse hovers over it, instead of just clicking i ...

Troubleshooting Angular 2 routerLink functionality issues

I have gone through all the tutorials and still can't figure out what I am doing wrong. AppModule : import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } fr ...

Having difficulty generating an Angular 5 Universal server application bundle with @ngtools/webpack

I am currently working on developing a cross-platform app using Angular 5 and WebPack without utilizing the CLI. The main issue I am facing is that I am unable to get the express application to function properly, resulting in encountering the following er ...

Error: Can't access the 'http' property because it's undefined in Angular 2

Recently, I successfully integrated the gapi client into my Angular 2 application. However, I am now facing an issue where my http object is showing as undefined and I can't seem to figure out why. Here's the snippet of code that's causing ...

Error: The "res.json" method is not defined in CustomerComponent

FetchData(){ this.http.get("http://localhost:3000/Customers") .subscribe(data=>this.OnSuccess(data),data=>this.OnError(data)); } OnError(data:any){ console.debug(data.json()); } OnSuccess(data:any){ this.FetchData(); } SuccessGe ...

Encountering an Issue with Registering the Angular 7 Service Worker - Error with ngsw-worker

Problem: Encountering ERR_INVALID_RESPONSE and /ngsw-config.json:-Infinity Parser error when trying to access the ngsw-worker.js file in network traffic. Refer to the image below: https://i.stack.imgur.com/Ejozw.png Technology Used: Angular CLI with An ...

Switching from a vertical to horizontal tab layout in Angular 4 Material 2 using MD-Gridlist

I'm currently trying to modify the tabbing functionality within an MD-Gridlist so that it tabs horizontally instead of vertically. I've experimented with tab indexes but haven't had any success. My goal is to enable horizontal tabbing throug ...

Is there a way to seamlessly transition between different Angular components without having to refresh the entire webpage?

I'm currently working on implementing a navigation bar that allows users to switch between three components without having the navbar reload. The goal is for only the new component to load when the user clicks on a different section of the navbar, kee ...

Even after the component is destroyed, the subscription to the service observable continues to emit

I'm facing an issue with an observable in my service. The provided code below demonstrates this: @Injectable({ providedIn: 'root' }) export class MyService { public globalVariable: BehaviorSubject<string> = new BehaviorSubject(&ap ...

Combine form data from a reactive form into a string using interpolation

Currently, I am working with an object that has a string property embedded within it. The string in this property contains interpolation elements. For my user interface, I have implemented a reactive form with an input field. My goal is to display the ent ...

Obtain the coordinates of the pixel in an image on the canvas when a mouse

I am currently working on a project that involves using canvas. I have set a picture as the background of the canvas and would like to be able to get the original pixel point when clicking in the image area. In order to achieve this, I need to convert canv ...

Angular developers may encounter a dependency conflict while attempting to install ngx-cookie

I'm currently facing an issue while attempting to add the ngx-cookie package for utilizing the CookieService in my application. Unfortunately, I am encountering some dependency conflicts that look like the following: $ npm install ngx-cookie --save np ...