What is the best way to troubleshoot the type of data being sent to the subscriber of an Angular observable?

I am new to the world of Angular-7, RxJS-6, and Visual Studio Code. Currently, I am facing a challenge with debugging an Observable that is being returned to a subscriber, resulting in a "TypeError" at runtime. It seems like this issue is not uncommon among developers. Can anyone provide guidance on how I can identify what the subscriber is observing or spot any errors in the code below?

In More Detail

I am working on a basic proof of concept using Visual Studio Code and Angular-7 CLI to fetch the current system date/time from a server using Angular's httpclient and display it.

Take a look at the method instrument.service.ts::getSystemTimeDate() below. The HTTP request is successful as we get the following JSON response:

{
  "SystemDateTime": "2018-11-26T08:54:06.894Z"
}

Within the map operator, this response gets converted first to an object of type SystemDateTimeResponse and then to a Date. The goal is to return an Observable<Date> to subscribers. However, I am struggling with how the component subscribes to this Observable<Date>. At runtime, the subscriber in the method onTimeDateBtnClick() throws the error mentioned above:

ERROR
TypeError: You provided an invalid object where a stream was expected...

I suspect that my issue lies in not correctly returning an Observable and possibly messing up the use of the map operator. What am I overlooking here?


The Source Code

The key components in this snippet are:

timedate.component.html: contains a simple template

<p>
  Last time checked: {{today | date:'medium'}}
</p>
<button mat-button (click)="onTimedateBtnClick()">Update</button>

timedate.component.ts: defines the display property today and the event handler onTimedateBtnClick() which uses a data service for managing HTTP requests/responses to retrieve the current date/time from a server.

import { Component, OnInit } from '@angular/core';
import { InstrumentService } from '../instrument.service';
import { Observable } from 'rxjs';

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

  /** Display property */
  today: Date;

  /**
   * Constructor
   * @param - data service
   */
  constructor(private dataService: InstrumentService) {
  }

  ngOnInit() {
    this.today = new Date();  /// initialise with client's date/time
  }

  /**
   * User event handler requesting system time/date from the server
   */
  onTimedateBtnClick() {
    const http$: Observable<Date> = this.dataService.getSystemTimeDate();

    http$.subscribe(
      res => this.today = res,
    );
  }
}

instrument.service.ts: includes the getSystemTimeDate() method that returns an Observable<Date>. Though simplified, the code still results in failure to better understand donde exaggerated use of the map operator.

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

// App imports
import { SystemDateTimeResponse, SystemDateTimeUrl } from './instrument.service.httpdtos';


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

  constructor(private http: HttpClient) { }

  /**
   * Return the server date and time
   */
  public getSystemTimeDate(): Observable<Date> {
    // Convert the server response object into an observable date
    const responseObject: Observable<Date> =
    this.http.get<SystemDateTimeResponse>(SystemDateTimeUrl.Url).
      pipe(
        map(jsonResponse => {
          const newDto = new SystemDateTimeResponse(jsonResponse.SystemDateTime);
          const d = new Date(newDto.SystemDateTime);
          return d;
        }),
      );

    return responseObject;
  }
}

instrument.service.httpdtos.ts: Contains definitions for data transfer objects.

/** URL - Instrument system date/time */
export class SystemDateTimeUrl {
  public static readonly HttpVerb = 'GET';
  public static readonly Url = 'api/instrument/systemdatetime';
  public static readonly Summary = 'Query the instrument current date/time';
}

/** Response DTO */
export class SystemDateTimeResponse {
  constructor(public SystemDateTime: string) {} 
}

Answer â„–1

There are two approaches you can take to debug your application. If you are using Chrome, you can utilize the developer tools to add breakpoints in your webpack source code for debugging purposes. Finding the necessary sources may be a bit challenging, but once located, the process should be straightforward.

Alternatively, if you prefer using Intellij IDEA / WebStorm, you have the option to debug the app directly within your editor. To do this, you will need to install the JetBrains IDE Support extension in Chrome / Firefox and configure your editor by adding a new Configuration: Editor Configuration -> Javascript Debugger. Make sure to specify the correct port if your app is running on a different port. Once both the app and debugging configuration are set up, you can add breakpoints in your code (such as in callback functions or map functions) to inspect the variables at those points.

If you have any further inquiries, feel free to ask.

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

Identifying favorited items by a user within the result list obtained from a GET request

Through a GET request, I am seeking to identify which of the outcomes have already been favorited or liked by the current user using the unique id associated with each object. There is a service in place that can determine if the user has favored an object ...

What is the proper way to utilize a custom property that has been incorporated into my Pinia stores in a Typescript project?

Currently utilizing Vue 3 alongside Pinia; my api service is utilized for making requests to the api. I have included it as a property to ensure availability across all stores: In my main.ts file: import { http } from "@/services/http"; const s ...

Authenticating passports without the need for a templating engine

Seeking assistance with integrating Passport authentication using the Google strategy. Authentication with Google works, but upon returning to the express server, I aim to redirect to a client-side page along with profile data without utilizing a templatin ...

Achieving a Subset Using Functional Programming

Looking for suggestions on implementing a function that takes an array A containing n elements and a number k as input. The function should return an array consisting of all subsets of size k from A, with each subset represented as an array. Please define ...

The constructor in a Typescript Angular controller fails to run

Once the following line of code is executed cockpit.controller('shell', shellCtrl); within my primary module, the shell controller gets registered with the Angular application's _invokeQueue. However, for some reason, the code inside t ...

Tips on incorporating JavaScript files into Angular applications

Struggling to incorporate a JavaScript function into Angular, I have installed the plugin "npm I global payments-3ds". I copied the JavaScript files from node_modules and attempted to call them in my component. Below is an example: import { ...

The art of representing objects and generating JSON responses

As I dive into building a web application using NextJS, a versatile framework for both API and user interface implementation, I find myself pondering the best practices for modeling and handling JSON responses. Key Points In my database, models are store ...

Identify the general type according to a boolean property for a React element

Currently, I am facing a scenario where I need to handle two different cases using the same component depending on a boolean value. The technologies I am working with include React, Typescript, and Formik. In one case, I have a simple select box where th ...

What are the steps to initiating a phone call using Nativescript?

When I click the button, I want to initiate a phone call dialing the number displayed on the label. Here is my custom button: <ActionBar> <NavigationButton (tap)="onBackTap()" android.systemIcon="ic_menu_back"></NavigationButton> ...

​Troubleshooting findOneAndUpdate in Next.js without using instances of the class - still no success

After successfully connecting to my MongoDB database and logging the confirmation, I attempted to use the updateUser function that incorporates findOneAndUpdate from Mongoose. Unfortunately, I ran into the following errors: Error: _models_user_model__WEBPA ...

What is the best way to generate a variable amount of div elements with constantly changing content using Angular2?

I'm not entirely sure on the process, but I believe ngFor would be used in this scenario. Essentially, my goal is to generate the following div multiple times, with each iteration updating the value inside the brackets from 0 to 1, 2, and so forth... ...

Exploring the Concept of Dependency Injection in Angular 2

Below is a code snippet showcasing Angular 2/Typescript integration: @Component({ ... : ... providers: [MyService] }) export class MyComponent{ constructor(private _myService : MyService){ } someFunction(){ this._mySer ...

Updating the navigation bar in Node/Angular 2 and displaying the sidebar once the user has logged in

I am facing a challenge with my first project/application built using Angular 2, particularly related to the login functionality. Here is what I expect from the application: Expectations: When I load the login component for the first time, the navbar ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

Typescript is throwing a fit because it doesn't like the type being used

Here is a snippet of code that I am working with: import { GraphQLNonNull, GraphQLString, GraphQLList, GraphQLInt } from 'graphql'; import systemType from './type'; import { resolver } from 'graphql-sequelize'; let a = ({Sy ...

The Art of Typing in TypeScript Classes

I am working with an interface or abstract class in TypeScript, and I have numerous classes that implement or extend this interface/class. My goal is to create an array containing the constructors of all these subclasses, while still ensuring that the arra ...

What is the best way to transform all elements on a webpage into a dynamic scrolling marquee?

Is there a way to make every div in a web application scroll like a marquee? Perhaps by using a specific CSS class or other method? The application is built with Angular 4 and Bootstrap. ...

Prevent additional functions from running when clicking in Angular 5

I have implemented an Angular material table where each row expands when clicked. In the last cell of the table, I load a component dynamically using ComponentFactory. This loaded component is a dropdown menu. The problem arises when the dropdown menu is ...

Attempting to launch an Angular web application on Azure's Linux-based Web App service

Currently, I am in the process of deploying my angular web app onto a free tier azure web app service for testing purposes. The deployment itself is done using an Azure pipeline and seems to be successful according to the logs found in the Deployment Cente ...

Utilizing React and TypeScript: Passing Arguments to MouseEventHandler Type Event Handlers

Can you help me understand how to properly define the event handler handleStatus as type MouseEventHandler, in order to pass an additional argument of type Todo to the function? interface TodoProps { todos: Array<Todos> handleStatus: Mous ...