When subscribing to an Observable of type number or string (union type), NaN values are returned for string inputs

Within a component, I have a public member that is defined as follows:

public docId$: Observable<number | string>;

This means that the document ID can either be an integer or a string. Upon initializing in ngOnInit, I have the following code snippet:

this.docId$.subscribe(value => {
    // perform operations using the value
    // when the value is a string, it evaluates to NaN
});

Unfortunately, this setup doesn't handle cases where the document ID is a string properly. The value ends up being NaN. Is there a way to make observables of union types work correctly in this scenario?

Answer №1

Utilizing the union type seems to be functioning fine. Take a closer look at the data you're receiving. Here is an example that works: https://stackblitz.com/edit/angular-rur73e

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

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

  private subject = new Subject<number | string>();
  public documentId$: Observable<number | string> = this.subject.asObservable();

  ngOnInit() {
  this.documentId$.subscribe(value => {
    // process value
    // NaN is returned when value is a string
    console.log(value);
  });
  this.subject.next("abc");
  this.subject.next(3);
  this.subject.next(Date.now());
  }
}

The output displayed in the console is:

abc
3
1571682486949

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

The combination of Object.keys() and the find function

Having trouble figuring out why I'm getting an error when attempting to use ES6 .find on the following data in order to retrieve the record with id number 3. { {id:10,title:'Dairy & Eggs'} {id:7,title:'Laundry & Household'} {id ...

How to stop a checkbox from being selected in Angular 2

I have a table with checkboxes in each row. The table header contains a Check All checkbox that can toggle all the checkboxes in the table rows. I want to implement a feature where, if the number of checkboxes exceeds a certain limit, an error message is ...

Can you send the value of an Angular-generated input to a function even if it doesn't have an ID associated with it?

Is there a way to make the cells in a dynamically generated table editable? The challenge I am facing is that because the table uses MatTableDataSource in Angular with data from an API, the cell elements cannot have unique IDs. How can I ensure that when a ...

How to remove a specific type from a generic type in Typescript without using Exclude<>?

I am looking for a solution to prevent my function from working with Moment objects when storing values in local storage. Currently, the function dynamically stringifies and stores values, but I want to exclude Moment objects from being processed. Here is ...

Encountering a "Error: Uncaught (in promise): EmptyError: no elements in sequence" due to the presence of multiple Angular 9 Route Resolvers

Why do I encounter an error when attempting to use multiple resolvers in Angular routing? If I remove one of the route resolves, everything works fine. But as soon as I include both, the error occurs. https://i.stack.imgur.com/WFI5C.png https://i.stack.im ...

Utilizing Router Outlet in Angular to Access API Data

I've encountered an issue where I can't pass parent data from the ngOnInit route params to my child component, user-seminar. After some research and searching on Google, I found a solution involving services. To address this problem, I modified ...

RTK update mutation: updating data efficiently without the need to refresh the page

I am facing an issue with my mui rating component in a post-rating scenario. Although the rating updates successfully in the data, the page does not refresh after a click event, and hence, the rating remains enabled. To address this, I have implemented a d ...

Scheduled task for sending emails using NodeJS

Currently working on my debut Node + Express app (MEAN) and seeking to integrate automatic email sending feature. Idea is for users to set reminders that the mailer will dispatch on specified dates. Considering incorporating the default Nodemailer + Node ...

Sending JSON RPC post requests in Angular 4

Attempting to retrieve JSON RPC data from the server using Angular 4 HttpClient. The error message received is {code: -32600, message: "INVALID_JSON_REQUEST: The JSON sent is not a valid JSON-RPC Request object"}. The command used is: curl -i -X POST -d ...

Modify the name of the document

I have a piece of code that retrieves a file from the clipboard and I need to change its name if it is named image.png. Below is the code snippet where I attempt to achieve this: @HostListener('paste', ['$event']) onPaste(e: ClipboardE ...

Visual Studio 2015 does not support compiling typescript files

I'm encountering some difficulties while attempting to set up node with typescript support in Visual Studio 2015 for my web API application. To start fresh, I deleted the node_module folder along with the package.json and tsconfig.json files. Followi ...

Executing a function within JSX to dismiss a modal in NextJS

I am currently utilizing the Tanstack React Query library to perform a POST request from a Modal that includes a form: const addDay = (day: TDay) => { const apiURL = process.env.NEXT_PUBLIC_SERVER_URL const queryURL = apiURL + router ...

Tips for capturing an error generated by a child component's setter?

I've created an App component that contains a value passed to a Child component using the @Input decorator. app.component.html <app-child [myVariable]="myVariable"></app-child> app.component.ts @Component(...) export class AppC ...

Customize the style of Angular Material within an Angular component

In my Angular component, I am utilizing Material 2's <md-input-container>. I am looking to customize a specific class, such as .mat-input-wrapper, that is originally defined in Angular Material. However, my intention is for this customization to ...

Eliminate the usage of JSON.stringify in the Reducer function

I have a system where I store chat messages in a dictionary with the date as the key and a list of messages as the value. Whenever a new message is added, the following code snippet is executed. Is there a way to enhance the existing code to eliminate the ...

During the process of adding a new template to my Angular project, I came across an issue within the core.min.js and script.js files

index.html <html class="wide wow-animation" lang="en"> <body> <app-root></app-root> <!-- Javascript--> <script src="assets/js/core.min.js"></script> <script src="assets/js/script.js"></script& ...

Developing Your Own Local Variable in Angular with Custom Structural Directive ngForIn

I am hoping for a clear understanding of this situation. To address the issue, I developed a custom ngForIn directive to extract the keys from an object. It functions correctly with the code provided below: import {Directive, Input, OnChanges, SimpleChan ...

Module Z encountered an unforeseen issue with the import of value X while utilizing the --aot flag

My application experiences significant slowness while loading in the browser (not to mention on mobile, taking 10-15 seconds). Even after running ng build --prod, the performance remains an issue. Attempting to address this with Angular CLI beta 16, I tri ...

By utilizing custom typeRoots while continuing to export these types alongside the entry point

For my project setup, I employ rollup to bundle an associated index.d.ts (and index.js) for the entrypoint src/index.ts. Within the project structure, there exists a directory named src/types containing multiple .d.ts files. These types are globally acces ...

Update the options in a dropdown menu after submitting a modal form

In my scenario, I have a modal form called "AddProductComponent" which is utilized within the "AddServiceRecordsComponent". export class AddProductComponent implements OnInit { id!: string; isAddMode: boolean = false; constructor(private fb: FormBuilder, ...