The service that offers an Observable on a specific subject is not receiving any notifications

The EventSpinner component is designed to subscribe to icons provided by the EventsService.

@Component({
    selector: 'event-spinner',
    template: `
<div class="col-xs-5">
    Test <i class="fa fa-2x" [ngClass]="{'fa-check': icon == 'ok', 'fa-spin': icon == 'loading', 'fa-spinner': icon == 'loading', 'fa-times': icon == 'error'}" id="spin"></i>
</div>
  `
})
export class EventSpinner implements OnInit {
    icon: string;

    constructor(public eventsService: EventsService) {
    }

    ngOnInit(): void {
        this.eventsService.icons.subscribe((icon) => {
            let old = this.icon;
            this.icon = icon;
            console.log("this.icon = " + this.icon + " (was " + old + ")");
        });
    }

}

When a web service request using @angular/http.get state changes ("loading"/"ok"/"error"), icons.next is called. However, there seems to be an issue where the class of the i tag doesn't get updated. Any ideas on how to resolve this?

EventsService.ts

@Injectable()
export class EventsService {
    icons: Subject<string> = new Subject<string>();

    constructor(public http: Http) {
    }

    subscribe(): Observable<Event[]> {
        let url = (<any>window).__ext.API_URL + 'event/view';
        let obs;
        return Observable
            .create((o) => {
                obs = o;
                obs.next();
            })
            .flatMap(() => {
                this.icons.next("loading");
                console.log("executing request");
                return this.http.get(url)
            })
            .retryWhen(error => {
                this.icons.next("error");
                return error.delay(3000);
            })
            .map((response: Response) => {
                this.icons.next("ok");
                console.log("response received");
                setTimeout(() => {
                    console.log("pushing next");
                    obs.next();
                }, 1000);
                return (<any>response.json()).map(item => {
                    return item;
                });
            });
    }
}

Answer №1

Perhaps the root cause lies in how EventService is implemented or there could be a potential issue with ngClass. One possible workaround is to manually trigger change detection as shown below:

export class EventSpinner implements OnInit {
    icon: string;

    constructor(public eventsService: EventsService, private cdRef:ChangeDetectorRef) {
    }

    ngOnInit(): void {
        this.eventsService.icons.subscribe((icon) => {
            let old = this.icon;
            this.icon = icon;
            console.log("this.icon = " + this.icon + " (was " + old + ")");
            this.cdRef.detectChanges();
        });
    }
}

Answer №2

After implementing:

new Observable(...);

and

new BehaviorSubject(...);

in place of the hardcoded

X.create();

I was able to resolve all of my problems.

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

Issues with Angular 2 loading properly on Internet Explorer 11

We are currently running an Asp.net MVC 5 web application integrated with Angular 2. The application functions smoothly on Chrome, Firefox, and Edge browsers, but encounters loading issues on IE 11, displaying the error illustrated in the image below: ht ...

Using an array of objects as a data source for the Material Angular table

My user data is causing some issues and looks like this... [{"firstName":"Pinkie","lastName":"Connelly","username":"Darlene.Marvin","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="19506a767b7c75464b7c77777c6b5971766d74 ...

Developing a Typescript npm package

In my project, there is a directory called models (named my-models) which houses several important typescript classes for my application. While I have been able to use these classes within the app without any issues, I now wish to turn it into an npm pack ...

Effective methods for transmitting reactive form control between child and parent components in Angular 2

I am working with a nested reactive form structure and I have the following setup: Parent HTML Code <form> <child-component></child-component> <button mat-raised-button color="primary">Save</button> </form> Child HT ...

Using Angular 2 to assign unique ids to checkbox values

Is there a way to retrieve the value of a checkbox in Angular 2 without needing an additional Boolean variable? I am trying to toggle the enabled/disabled state of an input field based on the selection of a checkbox. While I know this can be accomplished ...

Guide on setting up @types from an NPM module containing the "@" symbol in its title

Installing the node package is easy npm install @gamestdio/timer --save But when attempting to add the corresponding types npm install @types/@gamestdio/timer --save An error occurs Invalid package name "@types/": name can only include URL-friendly ch ...

Strategies for implementing ID passing in Angular's Ngrx effects

To show the information of the selected list, I will be choosing a list first. ...

React: State updates are not reflecting in the UI components

I am facing an issue where a function component is not updating visually when the state changes. To illustrate this problem, I have included a simple example of my component in which I update the state but the component does not reflect these changes in t ...

Integrate a @Component from Angular 2 into the Document Object Model of another component

One of my components is called TestPage import { Component } from '@angular/core'; @Component({ selector: 'test-component', template: '<b>Content</b>', }) export class TestPage { constructor() {} } Another ...

Updating a unique field with the same value causes a failure in the TypeORM update process

I am working with a service model in TypeORM, where I have a field called service_name that must be unique. However, when I attempt to update the table with the same value for service_name, it triggers a unique constraint violation error. I'm puzzled ...

Ensure the variable is valid by using a type guard in the false branch

I am attempting to use a type guard to narrow down a complex type. In my scenario, I want the false branch of the type guard to recognize the complement of the narrowed type. interface Model { side: 'left' | 'right'; } interface LeftMo ...

What is the best way to eliminate the # symbol in angular 5 URLs?

Currently, I am working on a project in Angular 5 and I need to remove the hash symbol (#) from my URL. The current URL looks like this: http://localhost:4200/#/product/add. While it works fine after being published on my domain, I encounter a 404 error ...

Tips for defining the anticipated server response solely based on status and cookie

I am using Redux Toolkit Query to occasionally refresh the jwt token: import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; export const refreshApi = createApi({ reducerPath: "apiSlice", baseQuery: fetchBaseQuer ...

Eliminate apostrophes in a string by using regular expressions

Can someone help me with this word What is The Answer? I need to eliminate the space and apostrophe '. To remove spaces, should I use this method: data.text.replace(/ +/g, ""). But how can I remove the apostrophe? ...

The synchronization between Typescript and the HTML view breaks down

I am currently working on an application that retrieves user event posts from MongoDB and displays them in HTML. In the Event-post.ts file, inside the ngOnInit() function, I have written code to retrieve the posts using the postsService.getPosts() method. ...

What causes the "node: bad option" error to occur when I include a custom flag in the nodejs command line within an Angular 9 application?

Seeking assistance with adding a custom flag to the npm start command in an Angular 9 project. The goal is to intercept proxy requests within the local server and manipulate data. However, encountering the "node: bad option" error consistently. Looking for ...

Improve your code by avoiding the use of multiple ngIf statements

Looking for ways to shorten my code for better readability. I have multiple ngIf statements with various conditions for numbering lists (e.g., 1, 1.1, 1.1.1) Here is a snippet of the code from my template: <span *ngIf="...">{{...}}.</span> .. ...

The JsonFormatter is throwing an error because it is trying to access the property 'on' of an undefined variable

I have encountered an error while attempting to generate an HTML report using cucumber-html-reporter The error message is: Unhandled rejection TypeError: Cannot read property 'on' of undefined at new JsonFormatter (C:\path-to-project\ ...

Utilizing Angular2 Guard to Ensure False IdentityServer4 OIDC Security

After successfully authenticating a user and redirecting them back to the main site, the following code runs: <script src="https://cdnjs.cloudflare.com/ajax/libs/oidc-client/1.2.2/oidc-client.min.js"></script> <h1 id="waiting">Waiting... ...

Using Stack and Drawer Navigations Together in React Native Navigation(v6)

I am looking to merge Stack and Drawer navigations. I have multiple screens and wish to display select screen labels in the drawer tab. <RootNavigatorStack.Navigator> <RootNavigatorStack.Screen name="DrawerTab" component={DrawerNavig ...