Issue with detecting window resize event in Angular 7 service

I have a unique service that utilizes a ReplaySubject variable for components, but strangely the WindowResize event isn't triggering.

import { Injectable, HostListener } from '@angular/core';
import { ReplaySubject } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
  export class CustomWindowResizeService {

    windowWidth;

    constructor() {
      console.log("Custom Window resize service activated");
      this.windowWidth = new ReplaySubject(1);
    }

    @HostListener('window:resize', ['$event'])
    onResizing(event) {
      console.log("Width: " + event.target.innerWidth);
      this.windowWidth.next(event.target.innerWidth);
    } 
}

In the component, I've subscribed to it in the following manner:

import { CustomWindowResizeService } from './custom-window-resize-service';

constructor(private customWindowResize: CustomWindowResizeService) implements OnInit {

}

ngOnInit() {
    this.customWindowResize.windowWidth.subscribe(
        (value) => { console.log(value) }
    );
}

Although I can see the

Custom Window resize service activated
message being logged, neither the console.log statement in the Service nor the Component seem to be executed. Any assistance would be greatly appreciated. Thank you! :)

Answer №1

A HostListener is exactly what the name suggests - it listens for events on the host component. However, it's important to note that although you can conveniently use the additional bindings such as window, document, or body for a global listener, this does not mean that the HostListener will work inside a service.

In order to achieve that functionality within a service, there are alternatives such as using the Renderer, employing the simpler approach of window.addEventListener, or utilizing the RxJS fromEvent(window).

Alternatively, you can also add the @HostListener() decorator specifically to the AppComponent (and restrict it only to that component), and then have it emit the service observable from there.

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

Update the component to display the latest information from the Bryntum grid table

In the Vue component, I have integrated a Bryntum grid table along with a bar chart. Clicking on one of the bars in the chart should update the data displayed in the Bryntum grid table. However, I've encountered difficulty in reloading the entire Bryn ...

When attempting to test the service, an error occurred stating "subscribe is not a

Currently, I am working on writing a Jasmine test for testing service calls in Angular. To spy on the service, I have used jasmine.createSpyObj. However, I encountered an error message: this.agreementsService.getOutstandingAgreements(...).subscribe is not ...

Display Module within Component using Angular 5

In the application I'm working on, I want to incorporate a variety of progress-loader-animations such as spinners or bars. To achieve this, I've developed a module with a component. Now, I'm trying to figure out how to display the module&ap ...

The z-index overlapping problem in webkit browsers is a result of Angular 7 animations

I have implemented staggered animations in my Angular 7 application to bring elements to life upon page load. However, I am facing a strange z-index problem with one of my components. Here is the animation code: @Component({ selector: 'track-page& ...

Getting an Angular TypeError after upgrading to version 9? It seems that the property 'selectors' cannot be read from null

After upgrading my Angular app from v7 to v8 and then v8 to v9, I encountered an issue. My app works perfectly locally when I run ng serve, but when I build for production using ng build --prod and deploy the app, I get an error in the application's c ...

Creating a date format for a REST API using Typegoose and Mongoose

Currently, I am utilizing TypeScript for a server that is connected to a MongoDB database. To ensure consistency, I am defining the outputs using an OpenAPI file. When working with Mongoose, I have experience in defining dates like this: birthday: Dat ...

Encountering CORS Issue with Golang and Gin following a Redirect Situation

I am currently working on implementing Google OAuth2 in my Go web server using Gin. I have integrated two new endpoints - /google/sign-in and /google/callback. The former receives the request and redirects to the Google auth URL, while the latter is trigge ...

What is the best way to create TypeScript declarations for both commonjs modules and global variables?

Wanting to make my TypeScript project compatible with both the commonjs module system and globals without modules. I'm considering using webpack for bundling and publishing it into the global namespace, but running into issues with the definitions (.d ...

Issues encountered while attempting to use 'npm install' on Angular, leading to

Having trouble with npm i in my project. It's not working for me, but others can install it smoothly. I've checked all the node and angular versions, but I can't figure out what's missing. Could it be my laptop's compatibility? Ple ...

Transform a JSON array into an array of objects using typescript

I have a JSON array that I need to convert into an object type array JSON array [ 0:{code: "00125", scheme: "0001", plotNumber: "125", propType: "001", plotType: "001"} 1:{code: "190", scheme: "0001", plotNumber: "NA 190", propType: "001", plotType: "0 ...

I am a beginner in the world of Typescript/Angular, and I have encountered a compiling error TS2339. It seems that even when the condition *ngIf="x.length > 0;" should be false, the

I'm currently enrolled in a Typescript/Angular course where I am learning about the implementation of "*ngIf". During one of the lessons, the instructor provided an example using an empty array to demonstrate how it fails the condition and results in ...

How to execute a function in a child component that is declared in the parent component using Angular

Is anyone able to help me with an issue I am facing in my Angular project? I have two components, 'app' and 'child'. Within the child component, I have a button that calls a function defined in the app component. However, this setup is ...

Is there a way to verify if a user taps outside a component in react-native?

I have implemented a custom select feature, but I am facing an issue with closing it when clicking outside the select or options. The "button" is essentially a TouchableOpacity, and upon clicking on it, the list of options appears. Currently, I can only cl ...

Oops! The react-social-media-embed encountered a TypeError because it tried to extend a value that is either undefined, not a

I recently attempted to incorporate the "react-social-media-embed" package into my Next.js project using TypeScript. Here's what I did: npm i react-social-media-embed Here is a snippet from my page.tsx: import { InstagramEmbed } from 'react-soc ...

Expand the data retrieved from the database in node.js to include additional fields, not just the id

When creating a login using the code provided, only the user's ID is returned. The challenge now is how to retrieve another field from the database. I specifically require the "header" field from the database. Within the onSubmit function of the for ...

The element type 'x' in JSX does not offer any construct or call signatures

I have recently imported an image and I am trying to use it within a function. The imported image is as follows: import Edit from 'src/assets/setting/advertising/edit.png'; This is the function in question: function getOptions(row) { ...

Adding Profile Photos to Authenticated User Accounts in Firebase / Ionic: A Step-By-Step Guide

I have thoroughly gone through the Firebase Docs on "Managing Users" for web along with watching their instructional video on YouTube. Despite following the code they provide, I am encountering an error message that states: "Property 'afAuth' do ...

Type guards do not work properly on a union of enum types in TypeScript

Recently delved into the concept of Type Guards Chapter within the realm of Typescript However, I encountered an issue where my basic type guards failed to differentiate a union of enums. Why is this happening? enum A { COMMA = ',', PLUS = & ...

Is there a way to define an interface that consists of child objects as the type for a function that uses destructured props?

Is there an alternative to this method? import { client } from "./setupApi"; export const getLayout = ({ page, entity, list }: {page: string, entity: string, list: string}) => { return client.get("/secure/nav.json"); }; How do I ...

Using Angular CLI with ES6 instead of TypeScript for your development needs can offer a

Is there a way to utilize an ES6 transpiler such as Babel instead of TypeScript in an Angular CLI project? Are there any specific flags for specifying the script language, similar to using --style? Thank you. ...