When utilizing Angular 5's ReplaySubject, the correct inheritance of 'this' is not maintained

Encountering a peculiar issue with Angular 5 and TypeScript, my problem may not be accurately reflected in the title.

Initially, I had this working code:

Calendar Service

_$dateChange: EventEmitter<object>;
constructor() {
    this._$dateChange = new EventEmitter<object>();
}
get $dateChange() {
    return this._$dateChange;
}
public calendarChanged(): void {
    this._$dateChange.emit({});
}

Parent

...
y = 2;
constructor() {
    this.calendarService.$dateChange.subscribe(item => {
      this.load();
    })
}
abstract load();

EventsComponent

export class EventsComponent extends ParentComponent {
    x = 0;
    load() {
         console.log(this.x, this.y); // outputs 0 2
    }
}

After reading this answer, I realized that I needed to utilize ReplaySubject. Moreover, I identified an issue with EventEmitter elsewhere.

Subsequently, I made some modifications to the code by swapping EventEmitter with ReplaySubject and emit with next. The updated code only affects the calendar service:

Calendar Service

_$dateChange: ReplaySubject<object>;
constructor() {
    this._$dateChange = new ReplaySubject<object>();
}
get $dateChange() {
    return this._$dateChange;
}
public calendarChanged(): void {
    this._$dateChange.next({});
}

However, upon checking the console.log result, it displayed undefined 2! Attempting to use this.load().bind(this) or arrow functions like load = () => {} didn't resolve the issue, rather the latter resulted in an error stating that the function load doesn't exist.

Unable to pinpoint the root cause of the problem, my suspicion lies on ReplaySubject.

Answer №1

After diligent investigation, I have uncovered the root cause of this issue.

The culprit behind the scenes is the presence of a value in the parent constructor's $dateChange, leading to its resolution and subsequent triggering of this.load();. The execution sequence proceeds as follows:

  1. Parent constructor
  2. load method (resulting in the execution of console.log(this.x, this.y);)
  3. Initialization of eventsComponent properties (triggering x = 0;)

Connection to ReplaySubject

This phenomenon ties back to the nature of a ReplaySubject, possessing a buffer that holds a value causing immediate resolution within the parent constructor.

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

What could be causing the incomplete transmission of data to the mongodb database?

Can anyone help me with my Angular CRUD operation issue? I am facing a problem where only the _id is being stored in the MongoDB database when trying to add a new person. The rest of the data is not getting sent completely. Here's my code: var expres ...

Uploading Files to REST API using Angular2

Currently, I am developing a Spring REST API with an interface built using Angular 2. My issue lies in the inability to upload a file using Angular 2. This is my Java Webresource code: @RequestMapping(method = RequestMethod.POST, value = "/upload") publ ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

Access the RxJS subscription data once and save it for later reuse

Currently, I am retrieving plans from a service using RxJS: public class PlansListComponent implements OnInit { private plans$: Subject<PlanDTO> = new BehaviorSubject([]); ngOnInit():void { this.serverService .list() .subscribe( ...

The incorrect starting points for nested for loops

I'm facing an issue while utilizing a nested for loop to generate x and y coordinates for a method call. Strangely, the loop variables seem to be starting off at incorrect values when I check using console.log. What could be the reason behind this une ...

Navigating through the keys of a parameter that can assume one of three distinct interfaces in TypeScript: a guide

Here is a function example: function myFunc(input: A | B | C) { let key: keyof A | keyof B | keyof C; for(key in input) { let temp = input[key]; console.log(temp); } } The definitions for A, B, and C are as follows: interfa ...

Discover the power of merging multiple events in RxJS for efficient data retrieval and filtering

In various scenarios, I need to display a table of data with additional functionality for filtering and refreshing. The table is accompanied by two input fields - one for local filtering (searchLocal) and another for backend filtering (searchBackend). Ther ...

Setting up D3 on a Meteor Angular2 project

Currently, I am attempting to combine D3 and topojson within the context of Meteor + Angular2. import { Component } from '@angular/core'; import template from './d3map.component.html'; * import 'd3' @Component({ selector: ...

Restrain a Key according to the data type of its value within a universal category

I am currently working on creating a versatile function where the generic type is used to define its parameter. Here's an excerpt from this parameter : type Configuration<T> = { masterdata: T[], target: ???? } I am encountering difficu ...

How to Implement Materialize CSS in Angular?

I am seeking advice on the most effective way to integrate Materialize into my Angular project. I came across "ng2-materialize," which requires the installation of jQuery. However, it is recommended not to mix jQuery with Angular. The newer version of Mate ...

When canActivate returns false, the screen in Angular 2 will still be accessed

I am encountering a problem where my canActivate method is returning false, but still navigating to the blocked screen. This issue seems to only occur in Chrome, as everything works fine in IE. Here is how the canActivate method looks: canActivate(route: ...

When using react-hook-form within a .map() function, it encounters an issue causing it to fail - specifically, a TypeError message stating "Cannot read properties of undefined (reading '

Confused and frustrated here, I can't seem to get this form working properly. I have a Checkbox component that works fine when not in a loop, but as soon as I try to integrate it into a loop, everything breaks. Checkbox.tsx const Checkbox = React.for ...

What is the process for including the sqlite3 dependency in a VS Code extension?

I am currently working on a Typescript extension for VS Code that utilizes the sqlite3 library. My project.json file looks like this: "dependencies": { "sqlite3": "^4.0.2" }, "devDependencies": { "@types/mocha": "^2.2.42", "@types/node": ...

What does the "xxx" parameter represent in the ng g universal xxx command when using AngularCLI 6+?

In this scenario, what is the purpose of morningharwood-server? Can we find it referenced in the code? ng generate universal morningharwood-server --client-project morningharwood ...

Do interfaces in Typescript require nested properties to be mandatory?

My interface contains a nested object: export interface Person { PersonWrapper: { name: string; address: string email?: string; } } When attempting to create an object from this interface, it appears that name is not mandat ...

Creating a Mat Table in Angular 7 by Mapping an Object with an Array of Objects

I've been working on mapping one of my objects to a mat-table. The input object from the Web API looks like this: [ { "inventoryId": 1004, "inventoryName": "Red Shirt Material", "dateReport": [ { ...

What is the best way to determine the type of `rootReducer`?

My project is set up with a combination of React, Redux, Immutable.js, and TypeScript. As I worked on implementing it, I made an effort to declare types wherever possible which led me to discover an interesting issue. A code example illustrating the proble ...

The onChange event does not work as expected for Select controls

I am facing an issue with my common useForm.tsx file when handling the onChange event for select controls. The error message I encounter is displayed below. Does anyone have any suggestions on how to resolve this? Error: Type '(e: ChangeEvent<HTM ...

Angular5: At what point does Angular finish loading a page?

Within my angular5 application, I have implemented a table that retrieves data from the backend. After the initial load of the table, I aim to adjust the scroll position inside it. To achieve this, I am utilizing the following code: ngAfterViewInit() { ...

Determining the type of index to use for an interface

Imagine having an interface called Animal, with some general properties, and then either be a cat or a dog with corresponding properties. interface Dog { dog: { sound: string; } } interface Cat { cat: { lives: number; } } type CatOrDog = Cat | D ...