Issues with Rxjs pipe and Angular's Http.get() functionality are causing complications

Working with an Angular 4 Component that interacts with a Service to fetch data is a common scenario. Once the data is retrieved, it often needs to be transformed and filtered before being utilized. The prevailing method for this task is through the use of pipes.

Within my Component:

ngOnInit(): void {
    this.suService.getShippingUnitTypes().subscribe(res => {
        console.log("Getting shipping unit types: ", res);
    });
}

Inside my service:

getShippingUnitTypes(): any {
    const convertToJson = map(value => (value as any).json().XXETA_GRID_STATIC_LOV);
    const filterShippingUnit = filter(value => (value as any).LOV_TYPE == "SHIPPING_UNIT");

    return this.http.get(
        this.constantsService.LOOKUP_COLUMN_BATCH_URL
    ).pipe(convertToJson, filterShippingUnit);
}

The service includes the following imports:

import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers, RequestMethod } from '@angular/http';
import { Observable, pipe } from 'rxjs/Rx';
import { map, filter } from 'rxjs/operators';

While debugging, the code runs without errors but fails to reach the console.log() statement in the Component. Removing the .pipe() and returning the Observable logs the expected output without any transformations or filters being applied.

Being new to Rxjs and using Pipe, there's clearly a misunderstanding on my part.

Additional information reveals:

I incorporated tap into the pipe like this...

pipe(tap(console.log), convertToJson, tap(console.log), filterShippingUnit, tap(console.log))

Discovering tap proved to be beneficial. The first two console logs present the anticipated results. However, the third one, after the filterShippingUnit, doesn't produce any output whatsoever. It doesn't even log a null value.

Following the convertToJson operation, console.log displays an array of 28 objects. One particular object is:

{LOV_TYPE: "SHIPPING_UNIT", LOV_TAB_TYP_ITEM: Array(4)}

Expectations dictate that this object should undergo the filterShippingUnit filtration process.

Answer №1

The issue likely lies in this section of code:

const filterShippingUnit = filter(value => (value as any).LOV_TYPE == "SHIPPING_UNIT");

Assuming that after converting the response body to JSON, you receive an array of objects of type Foo, where Foo is defined as:

interface Foo {
 LOV_TYPE: string;
 fooProperty: string;
 fooNumber: number;
}

Your current attempt filters the array object rather than its individual elements.

You can either flatten the array, process each element individually, then reassemble them into an array, or map the array to a new one. The latter option is simpler, like so:

const filterShippingUnit = map((list: Foo[])=> list
              .filter(foo => foo.LOV_TYPE === "SHIPPING_UNIT"));

The alternate approach could be implemented as follows:

import { flatMap, toArray } from 'rxjs/operators';

return this.http.get(this.constantsService.LOOKUP_COLUMN_BATCH_URL)
    .pipe(
      flatMap(response => response.json() as Foo[])
      map(foo => foo.LOV_TYPE === "SHIPPING_UNIT") // TypeScript will infer that foo is of type Foo
      toArray
     );

Since you seem new to Angular, I recommend these steps:

  • Create interfaces for data fetched from the backend
  • Utilize the new HttpClient API in Angular instead of the deprecated Http module (consult https://angular.io/guide/http)
  • Avoid defining constant functions for stream operations without specifying argument types explicitly, as it may result in loss of type information. Some argue that even when TypeScript can infer types, explicitly declaring them is a good practice...

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

@ViewChild not functioning properly when element exists in child component

Imagine we have a component called "ParentComponent" ParentComponent.html <div> <child1></child> </div> Child1.html <h1 #childH1> Ezzy </h1> If we try to access the element with id "childH1" from "parentComponen ...

NestJS Ensures Type Safety for Mongoose Models, but Model Functions Expecting Incorrect Types (Any)

Shema Interfaces export interface MyCat { name: string; color: string; } export type Cat = MyCat & Document; export const CatSchema = new Schema({ name: { type: String, required: true, }, color: { type: String, required: tr ...

Only one radio button in Angular2 remains enabled

On a page, I have a set of radio buttons grouped into "Yes" or "No" buttons. Depending on the value of a variable, I want to disable them. However, only the "Yes" button is disabled when initially loading the page. There is also a drop-down that changes ...

While using axios to make a GET request, I encountered errors when checking for .isSuccess in react

const searchInvoiceList = async ( plantLocation: string, invoiceType: string ) => { let dataList: InvoiceData[] = []; await axios .get(`${linkURL}inv/getControlList/${plantLocation}/${invoiceType}`) .then((response) => { dataLis ...

Using `reduce` in TypeScript, you can organize an array of objects based on a shared property

Here is an example of an array: [ { id: '1', task: 'Grocery shopping', isImportant: true }, { id: '2', task: 'Meeting', isImportant: false }, { id: '3', task: &apos ...

Why is it that I am limited to running globally installed packages only?

Recently, I made the switch to Mac iOS and encountered an issue while setting up a new TypeScript backend project. All npm packages seem to be not functioning properly in my scripts. Cannot find module 'typescript/bin/tsc' Require stack: - /Users ...

Issue with importing aliases in Angular 7 production environment

Hello everyone! I have encountered an issue where using alias on import and building the project in production mode (--prod flag) results in the alias being undefined. Interestingly, this behavior does not occur in development mode. Any suggestions on how ...

Error in Typescript occurring with a custom typography element

I recently developed a simple typography component for my React project and it's causing a Typescript error that's puzzling me a bit. Typography Component Code import clsx from 'clsx'; const sizeVariants = { h1: 'h1', ...

Creating Angular UI states with parameters in TypeScript

My Understanding In my experience with TypeScript and angular's ui state, I have utilized "type assertion" through the UI-Router definitely typed library. By injecting $state into my code as shown below: function myCtrl($state: ng.ui.IStateService){ ...

Typescript-enabled NodeJS REST client

I'm currently working on a nodejs web application using express and I want to access my API. I have experimented with various options, such as restangular and jquery ajax calls. Can anyone recommend some reliable REST client libraries with TypeScrip ...

Is there a method to uncover the code that controls the display of a <div> element?

As a fresh face at the company, I've been given the responsibility of developing a chart that is similar to one already present on their website. While I have the knowledge and skills to create it, I am struggling to locate the specific code where the ...

Angular 4 Bootstrap 4 Collapsible Navigation Bar

Struggling for a while now trying to achieve the exact functionality I desire. Within my Angular Universal App, there is a vertical navigation bar at the top that I want to make responsive for mobile devices. I am utilizing Bootstrap 4 Alpha 6 and ngx-boot ...

Unable to render React component after updating its state

After successfully retrieving data from my API, React is failing to render the cards. export default function Subjects() { const userApi = useUserService(); const auth = useRecoilValue(AuthAtom); const [loading, setLoading] = React.useState<boolea ...

Change the value of the material slide toggle according to the user's response to the JavaScript 'confirm' dialogue

I am currently working on implementing an Angular Material Slide Toggle feature. I want to display a confirmation message if the user tries to switch the toggle from true to false, ensuring they really intend to do this. If the user chooses to cancel, I&ap ...

Determining Cost Using Quantity and Option Changes in Angular 4

Task In the shopping cart, there is a list of items with options, quantities, and prices. The goal is to calculate the total price based on any changes in the quantity and option of an item. Investigation I included [(ngModel)] for 2-way data binding, ...

What is the best way to connect my Typescript NextJS code to my Express API?

My goal is to extract data from my API, which is providing the following JSON: [ { project: "Challenges_jschallenger.com" }, { project: "Using-Studio-Ghilis-API-With-JS-Only" }, { project: "my-portfolio-next" }, { proj ...

Encountering issues with Angular2 forms while working with JavaScriptServices/Universal

My Angular2 app was built using the JavaScriptServices starter from GitHub. The issue I'm encountering is a runtime error when I include a form in a component. Both FormsModule and ReactiveFormsModule are being imported. This is how my form is stru ...

Launch the flutter application's web browser and seamlessly navigate back to the app

Currently, I am in the process of developing a mobile application with Flutter, alongside a web version using Angular and Node.js for the backend. I have found myself in need of a unique workflow that involves redirecting users to the web application duri ...

Setting Values in Angular Reactive Forms Programmatically

I am working on an Angular Reactive Form that includes validation. I need assistance with properly calling the setter for my hiddenComposedField. app.component.ts ngOnInit() { this.myForm = this.formBuilder.group({ 'field1': ['' ...

Is Typescript reliable when working with a reference to a DOM element?

In this scenario, a function is provided with the task of obtaining a reference to a DOM element and executing certain actions: function getElementAndDoStuff() { // element: HTMLElement | null const element = document.getElementById('id'); ...