The shared service is malfunctioning and displaying inconsistent behavior

app.component.ts

import { Component } from '@angular/core';
import { HeroService } from './hero.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'aditya';

  constructor(private service : HeroService)
  {}
  sender()
  {
    this.service.addchanges("ab");
    this.service.addchanges("cd");
    this.service.addchanges("ef");
  }
}

app.component.html

<h3 (click)="sender()">Click me to send the value</h3>
<app-detail></app-detail>

hero.service.ts

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

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

  constructor() { }

  area = new Subject();

  changeemitted = this.area.asObservable();

  addchanges(change)
  {
    console.log("entered at service");
    console.log("chnage getted",change);
    this.area.next(change);
  }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { DetailComponent } from './detail/detail.component';
import { HeroService } from './hero.service';

@NgModule({
  declarations: [
   AppComponent,
   DetailComponent
 ],
 imports: [
   BrowserModule
  ],
 providers: [HeroService],
  bootstrap: [AppComponent]
})
export class AppModule { }

detail.component.ts

import { Component, OnInit } from '@angular/core';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.css']
})
export class DetailComponent implements OnInit {

  constructor(private serviceFetcher:HeroService) {
  }

  ngOnInit() {
  }

  caller(){
    console.log("caller entered");
    this.serviceFetcher.area.subscribe(text => console.log("text detail",text));
  }
}

detail.component.html

 <p (click)="caller()">
 detail works!
 </p>

After successfully sending values through sender(), the subscribe method in caller() is not getting called as expected, only "caller entered" is displayed in the console. detail.component.ts:22 caller entered detail.component.ts:29 ___________________________ However, upon sending values through sender() again without refreshing, the subscribe method is triggered as expected.

  hero.service.ts:19 entered at service
  hero.service.ts:22 chnage getted ab
  detail.component.ts:23 text detail ab
  hero.service.ts:18 ___________________________
  hero.service.ts:19 entered at service
  hero.service.ts:22 chnage getted cd
  detail.component.ts:23 text detail cd
  hero.service.ts:18 ___________________________
  hero.service.ts:19 entered at service
  hero.service.ts:22 chnage getted ef
  detail.component.ts:23 text detail ef

I have tried debugging but it seems the "text detail" is not visible. Is this a specific behavior of Subject in Angular? Appreciate any guidance on the issue as I am new to Angular and eager to learn more. Please let me know if there is an error in my approach instead of dismissing it outright. I aim to retrieve data when calling the caller() method.

Answer №1

It is essential to avoid repeatedly subscribing to an observable as it can lead to memory leaks.


    private subscription: Subscription; // Remember to unsubscribe in the onDestroy method

    initiateCaller() {
        if (!this.subscription) {
            this.subscription = this.dataService.fetchData.subscribe((response) => {
                console.log(response);
            });
        }
    }

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

Unable to see Next.js page in the browser window

I have set up a next.js project with App Router and my file structure under the app folder looks like this: *some other files* . . user | [id] | | page.tsx | @users | | page.tsx | layout.tsx | page.tsx I am ...

Having trouble with JavaScript's Date.getUTCMilliSeconds() function?

I have a straightforward question for you. Take a look at this Angular App and try to create a new date, then print the number of UTC milliseconds of that date in the console. Can you figure out why it is returning zero? ...

Creating QR codes from raw byte data in TypeScript and Angular

I have developed a basic web application that fetches codes from an endpoint and generates a key, which is then used to create a QR Code. The key is in the form of an Uint8Array that needs to be converted into a QR Code. I am utilizing the angularx-qrcode ...

The element 'p-checkbox' is unrecognized in primeng version 4

Currently utilizing primeng version 4. I have included a p-checkbox in my template and imported it to the respective TypeScript file. However, upon loading the page in the browser, an error stating "'p-checkbox' is not a known element" keeps appe ...

Incorporating scope injection similar to AngularJS into newer libraries

My current platform is built using AngularJS, and I'm considering transitioning to a more modern framework in the future. However, I have concerns about dynamic scope injection when it comes to ES6, Webpack, and TypeScript. Our use-case involves dynam ...

How can I use Angular2 to draw a square [input] number of times?

I need to create a specific number of squares within a container using Angular2. Can you please provide me with a straightforward example, preferably utilizing canvas? Currently, I have converted webpack starter for use with Angular: This is the code ins ...

What causes an inference site to have varying effects when accessed directly versus when it is retrieved from a function?

Below is the provided code snippet : declare class BaseClass<TValue = any> { value: TValue; foo(value: TValue): void; } type Wrapped<T> = { value: T } declare class ConcreteClasss<TValue> extends BaseClass<TValue> { construc ...

Typescript's Patch<T> type enforces strictness within the codebase

There have been instances where I needed to 'patch' an object T using Object.assign(). For instance, when propagating changes you might modify a stateful object that other code references (common in reactive programming like MobX or Vue). It&ap ...

Can someone guide me on integrating a React Material-UI Component into an Angular2 application?

I've been searching for documentation on integrating ng2 and React, but it's been hard to find any solid information. It's making me question whether or not these two can actually work together. Since I'm not an expert, I could really u ...

What is the best way to change `props.children` into a JSX element?

When using React functional components, we have the ability to render children in the following way: import React from 'react'; const MyComponent = (props: React.PropsWithChildren) => { return props.children; } However, I encountered an ...

Using a for loop in conjunction with Observable.forkJoin

In my component, I am striving to populate an array known as processes, containing individual process objects that each have a list of tasks. Currently, I am dealing with two API calls: /processes and /process/{processId}/tasks I utilize the /processes ...

Ways to fetch information from NGRX store in a linear manner

Struggling to handle NGRX's data access patterns effectively. Currently, I am retrieving data from my NGRX store in the following manner: logBooksAndAuthors() { const books$ = this.store.select(store => store.books); const authors$ = this.s ...

Adding Dynamic Controls in Angular 4: A Guide

For this illustration, I've put together a compact form that allows me to introduce dynamic controls by simply clicking on the "Add Pre-Phase" button. Once a few pre-phases are added, I will designate a phase type, and if the chosen value is EMS, the ...

The variable 'BlogPost' has already been declared within the block scope and cannot be redeclared

When working with Typescript and NextJS, I encountered the following Typescript errors in both my api.tsx and blogPost.tsx files: Error: Cannot redeclare block-scoped variable 'BlogPost'.ts(2451) api.tsx(3,7): 'BlogPost' was also dec ...

Removing an image from the files array in Angular 4: A step-by-step guide

I have recently started working with typescript and I am facing a challenge. I need to remove a specific image from the selected image files array before sending it to an API. app.component.html <div class="row"> <div class="col-sm-4" *ngFor ...

Having trouble with i18n types not functioning correctly in Typescript and Nuxt?

I am currently utilizing NuxtJS/i18n with TypeScript and have included its types in my TS config: { "compilerOptions": { "types": [ "@nuxt/types", "@nuxtjs/i18n", ] } } However, when attempti ...

Unable to execute function: Angular 7 Platform-Browser-Dynamic (intermediate value) share is not defined

Recently, I have been working on upgrading our Angular 5 build to version 7. After installing webpack 4, rxjs 6.3.3, and angular 7.0.3, along with taking care of dependencies, I managed to successfully compile the bundle. However, a puzzling error seems to ...

Converting an array into an array of objects using Node.js

I currently have a Node.js REST API that generates an array structured like this: [["Benni", 24, "Whatever"], ["Paul", 23, "Whatever"]] In order to integrate this array into an Angular Material table, I need to transform it into the following format: [{ ...

Do these two syntaxes for fat arrow functions differ in any way, or are they essentially the same in function?

I've noticed in Angular 6 / Typescript code examples that fat arrow functions are used with two different syntaxes. Is there any distinction between them, or do they perform the same functionally? blah.then(param => { // perform some action wi ...

Angular 2 fails to redirect to a 404 page if both the route parameter and address are not valid

Currently, while working on my application with Angular 4.1.1, I have a habit of declaring routing in every module I create. For instance, in the file new-cars.routing.module.ts: import { NgModule } from '@angular/core'; import { RouterModule, ...