The Angular variable binding issue persists upon reloading the page or browser, yet functions seamlessly when navigating between routes

My subscribe button displays the text "Subscribe" when the page loads, but upon reloading the page, the text disappears. The button text is controlled by TypeScript code, and strangely, when I navigate to another route, the text magically reappears.

HTML

<button type="button" (click)="subscribe()" name="subscribe" id="subscribe">
    <span *ngIf="!subscribeFormProcessing">Subscribe</span>
    <span *ngIf="subscribeFormProcessing"><img [src]="btnLoaderUrl"></span>
</button>

Typescript

export class FooterWidgetComponent implements OnInit, OnDestroy {

    subscribeEmailAddress: string;
    subscribeEmailSubscriber: any;
    btnLoaderUrl: string;
    subscribeFormProcessing = false;
    subscribeMsg: string;

    constructor(private appSettingsService: AppSettingsService, private httpRequestService: HttpRequestService) {
    }

    ngOnInit() {
        this.subscribeEmailAddress = '';
        this.subscribeMsg = '';
        this.btnLoaderUrl = this.appSettingsService.getImagesBaseUrl() + 'app/btn-loader.gif';
        this.subscribeEmailSubscriber = this.httpRequestService.requestCompleted.subscribe(data => {
            this.subscribeFormProcessing = false;
            if (data['status'] === "success") {
                this.subscribeMsg = data['message'];
            } else {
                this.subscribeMsg = data['message'];
            }
            this.clearSubscribeMessage()
        });
    }

    clearSubscribeMessage() {
        setTimeout(() => {
            this.subscribeMsg = '';
        }, 5000);
    }

    subscribe() {
        this.subscribeFormProcessing = true;
        this.httpRequestService.setUrl('subscribe');
        this.httpRequestService.sendPost({email: this.subscribeEmailAddress});
    }

    ngOnDestroy() {
        this.subscribeEmailSubscriber.unsubscribe();
    }

}

On Page Reload

After navigating to any route

Root Cause I am using Addthis widget for sharing post and blog. Initializing the addthis on blog page load seems to be causing this particular issue.

initAddThisToolbar() {
        addthis.layers.refresh();
    } 

HTML

<div class="addthis_inline_share_toolbox"></div>

Is there a different method to refresh the addthis widget?

Answer №1

When the page refreshes, the onDestroy() method is not called. This results in your description never being dropped and

this.httpRequestService.requestCompleted.subscribe()
not getting called a second time. The onInit() function still executes, causing this.subscribeFormProcessing to remain true.

To address this issue, you need to unsubscribe from this.subscribeEmailSubscriber during the reload process. Here is a possible solution:

ngOnInit(): void {
   // Check if there is an active subscription
   // If so, unsubscribe
   if (this.subscribeEmailSubscriber) {
       this.subscribeEmailSubscriber.unsubscribe();
   }

   // Rest of the code remains unchanged
   this.subscribeEmailAddress = '';
   this.subscribeMsg = '';
   this.btnLoaderUrl = this.appSettingsService.getImagesBaseUrl() + 'app/btn-loader.gif';
   this.subscribeEmailSubscriber = this.httpRequestService.requestCompleted.subscribe(data => {
        this.subscribeFormProcessing = false;
        if (data['status'] === "success") {
            this.subscribeMsg = data['message'];
        } else {
            this.subscribeMsg = data['message'];
        }
        this.clearSubscribeMessage()
   });
} 

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

Converting Enum Values into an Array

Is there a way to extract only the values of an enum and store them in an array? For example, if we have: enum A { dog = 1, cat = 2, ant = 3 } Desired output: ["dog", "cat", "ant"] achieved by: Object.values(A) Unfor ...

Getting a list of the stack resources available in cloudformation using TypeScript

My team is developing an application that will deploy multiple stacks to AWS. One of these stacks is called SuperStar, and it can only exist once per AWS account. I am currently exploring how our TypeScript CDK can retrieve a list of stacks from CloudFor ...

Angular 4 has the capability to automatically log out in all tabs when a user logs out in one open tab

I am looking to implement a feature where I automatically log out from all open tabs when logging out from one tab. Currently, I am storing a jwt token in localStorage upon login and removing the token upon logout. Any suggestions on how I can utilize st ...

Expressions without a call signature cannot be invoked

When using an adapter in the given example, I encountered a type error specifically on the last line of the getGloryOfAnimal method. Despite having clearly defined types, I am puzzled by this issue. interface ICheetah { pace: string; } interface ILio ...

Reactify TypeScript: Accurate typings for onChange event

How can I resolve the issues with types for target: { value: any, name: any }? The errors I encounter include Duplicate identifier 'any'. and Binding element 'any' implicitly has an 'any' type.. Additionally, why does the erro ...

Error suddenly appeared when trying to serve a previously functional project locally: Firebase function module not found

After not making any changes to my firebase-related files, I suddenly started encountering the following issue that I just can't seem to figure out: We were unable to load your functions code. (see above) - It appears your code is written in Types ...

Exploring the process of linking a C# REST API to an Ionic 2 mobile application

I am completely lost on how to connect an asp.net web api with my ionic 2 mobile app. Any help or advice on resolving this problem would be greatly valued! ...

Dynamically access nested objects by utilizing an array of strings as a pathway

Struggling to find a solution for accessing nested object properties dynamically? The property path needs to be represented as an array of strings. For example, to retrieve the label, use ['type', 'label'] I'm at a roadblock wit ...

Utilizing External Libraries Added Through <script> Tags in React

My goal is to develop a Facebook Instant HTML5 application in React. Following their Quick Start guide, Facebook requires the installation of their SDK using a script tag: <script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></scrip ...

How can I retrieve all the data for the chosen item in a mat-select within a mat-dialog, while still preserving the code for setting the default selected value

In my modal dialog, I have a dropdown menu populated with various languages. The ID of the selected language is bound to the (value) property for preselection purposes when data is passed into the dialog. However, I am looking for a way to also display the ...

When conducting unit testing in Angular, it is important to avoid calling the Angular service if the return type is an observable of any when dealing

Using the Spyon function to mock a method call on a service and return an observable of 'TEST'. This method is for a service. Although similar methods with a class object return type are working fine in the debugger, there seems to be an issue wi ...

Utilizing TypeScript path aliases in a Create React App project with TypeScript and ESLint: A step-by-step guide

I utilized a template project found at https://github.com/kristijorgji/cra-ts-storybook-styled-components and made some enhancements. package.json has been updated as follows: { "name": "test", "version": "0.1.0" ...

Creating a class and initializing it, then implementing it in other classes within an Angular application

Trying to grasp some angular fundamentals by creating a class structure. Unsure if this is the right approach. export class Cars{ Items:Car[]=[]; constructor() { this.Items = [ { id: "1", name: "Honda" ...

Compiler error occurs when trying to pass props through a higher-order component via injection

Recently, I have been experimenting with injecting props into a component using a higher order component (HOC). While following this insightful article, I came up with the following HOC: // WithWindowSize.tsx import React, {useEffect, useMemo, useState} fr ...

A guide on retrieving bytecode from a specific PDF using Angular

Can anyone help me with extracting the bytecode from a selected PDF file to save it in my database? I keep encountering an error stating that my byte is undefined. Could someone please review my code and identify what might be causing this issue? I attemp ...

Guide on Creating a Custom Property within the Same Component in Angular 2

Having trouble defining a custom property called count. When I try to bind it, I get an error saying: Can't bind to 'count' since it isn't a known property of 'p'. How can I fix this issue and successfully make count a custom ...

React TypeScript Context - problem with iterating through object

Can someone please help me with an error I am encountering while trying to map an object in my code? I have been stuck on this problem for hours and despite my efforts, I cannot figure out what is causing the issue. Error: const categoriesMap: { item: ...

After clicking on the "Delete Rows" button in the table, a white color suddenly fills the background in Angular Material

When the dialog box pops up, you'll see a white background color: https://i.stack.imgur.com/EflOx.png The TypeScript code for this action can be found in config-referrals.component.ts openDialog(action, obj) { this.globalService.configA ...

Sharing information with a service in Ionic and Angular

I need to send data to my service and incorporate it into a URL string. The code snippet below shows how I am obtaining the data in my constructor when the user navigates to the page: constructor(public alertController: AlertController, pri ...

The e2e directory seems to be missing from my Angular project

https://i.stack.imgur.com/xzrlb.png Despite reinstalling the CLI, the E2E feature still eludes me. ...