To utilize RxJS 6+, the 'Observable' type needs to include a 'Symbol.iterator' function that generates an iterator

I encountered an issue when attempting to filter an array of values from an observable:

The error message I received was: 'Type 'Observable' must have a 'Symbol.iterator' method that returns an iterator'

Here is the code snippet:

export class ItemsService {

  orderItems: OrderItem[] = [];
  orderItemsUrl = 'http://localhost:5000/order-items/';

  getOrderItemsFromHttp(selectedOrderNumber): Observable<OrderItem[]> {
    const tempArr = [];
      const orderItems = of (this.http.get<OrderItem[]>(`${this.orderItemsUrl}`)
      .subscribe(res => {
            this.orderItems = res;
      }) );

    for (const orderItem of orderItems) {                        <--- The error occurs here
        if (orderItem.orderNumber === selectedOrderNumber) {
          tempArr.push(orderItem);
        }
    }
    return of(tempArr);
  }  
}

By changing the following:

for (const orderItem of orderItems) {

to

for (const orderItem of [orderItems]) {

The error disappears, but the property orderNumber is no longer recognized. IntelliSense then displays:

Property 'orderNumber' does not exist on type 'Subscription'

What is the best way to fix this issue?

Answer №1

It appears that the solution you are seeking is as follows:

  retrieveOrderItemsFromServer(orderNumber): Observable<OrderItem[]> {
    return this.http.get<OrderItem[]>(`${this.orderItemsEndpoint}`).pipe(
      map(orderItems => orderItems.filter(item => item.orderNuber === orderNumber))
    );
  }  

In order for this code to function properly, ensure you have imported the map operator:

import { map } from 'rxjs/operators';

Answer №2

To maintain flexibility in your codebase, I suggest decoupling your connection method from your business logic retrieval. This way, transitioning from using HTTP to SignalR, for instance, won't require changing your core logic.

You can achieve this by creating a separate service dedicated to handling HTTP requests for data retrieval. Your ItemsService can then utilize this service to fetch the necessary data.

There's no need to reconstruct the array unnecessarily.

@Injectable ({
   providedIn: 'root'
})
export class RestService {
config: Config; // Define your URLs
   getItems () {
     return this.http.get <OrderItem []> (this.config.itemURL, {note: 'response'});
   }
}

@Injectable ()
export class ItemsService {

  orderItems: OrderItem [];

constructor (private restService: RestService) {
}

getItems () {
   return new Observable ((observer) => {
    restService.getItems (). subscribe ((items) => {
      observer.next (items);
    });
  });
}

}

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

Having difficulty uploading a file using a formGroup

Currently, I am using Angular to create a registration form that includes information such as name, email, password, and avatar. For the backend, I am utilizing NodeJS and MongoDB to store this information. I have successfully written the registration API ...

What could be causing the "Failed to compile" error to occur following the execution of npm

Exploring react with typescript, I created this simple and basic component. import React, { useEffect, useState } from "react"; import "./App.css"; type AuthUser = { name: string; email: string; }; function App() { const [user, setUser] = useState& ...

Setting up ESLint for TypeScript with JSX configuration

I am encountering problems with TypeScript configuration. Below is the code snippet from my tsconfig.json: { "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLib ...

Cross-origin resource sharing (CORS): In PHP, the response to the preflight request is not successfully passing. I am permitting

With the abundance of CORS posts already out there, I find myself adding to them in search of a solution. My dilemma involves building an angular 4 application that interacts with my php api. Locally, everything works seamlessly. However, once I upload the ...

Utilizing a Material UI custom theme in React with Typescript: A step-by-step guide

Upon using the tool , I received a js file and a json file following the paths mentioned on the theme generator page: // src/ui/theme/index.js /* src/ui/theme/theme.json */ The files operate smoothly when left with the .js extension. However, when I attem ...

How to avoid property name conflicts when extending interfaces in Typescript

Is it possible to achieve something like this using TypeScript, such as renaming a property? interface Person { name: string age: number } interface Pet { age: string } interface Zoo extends Pet, Person {} How can we prevent this error from ...

TypeScript overlooking mismatched type arguments in generics

Currently, I am in the process of constructing a pluggable interface/class system that enables an "output" to connect with an "input". To my surprise, TypeScript seems to overlook any warnings or errors that might arise when a compatible interface is pai ...

A colleague's dependency is taking precedence over an NX Library

I'm working in a monorepo environment with nx, structured as follows: apps | - my-app libs | - common | - my-client After deployment, the libraries are published on npm with the names @my-org/my-client and @my-org/common. I have set up path ali ...

When I remove a datarow from my database, it continues to appear on my webpage until I manually refresh it. Is there a way to ensure that the row is instantly deleted from my table

I am currently utilizing WebApi for the backend and Angular 5 for the frontend. The WebApi is connected to a database from which I retrieve data to be displayed on my website. However, when I click on the "delete" button, the data gets deleted from the dat ...

Ways to programmatically include routes with components sourced from a dynamically loaded module

One of my Angular components is dynamic and module-based: The module file is named dynamic-component.module.ts @NgModule({ imports: [ DynamicComponentRoutingModule, FormsModule, CommonModule, FormsModule, ], declarations: [ ...

Is there a way to determine the present date within a template?

In my component, I am working with an object that contains a timestamp. What I aim to achieve is to dynamically check this timestamp in the template at runtime. For instance, I want to display the online status of a member by showing a green dot if they a ...

Angular - Is there a specific type for the @HostListener event that listens for scrolling on the window?

Encountering certain errors here: 'e.target' is possibly 'null'. Property 'scrollingElement' does not exist on type 'EventTarget'. What should be the designated type for the event parameter in the function onWindow ...

Incorporate a module that was developed locally into your project

Attempting to incorporate a locally developed Angular project/module into an angular application without having to publish it on the npm repository has been quite a challenge for me. To begin with, I decided to follow a tutorial that guided me through bui ...

Refresh the Angular2 API at regular intervals to monitor any updates in the response

Is it possible in Angular 2 to monitor changes in the API? Here is my scenario: I upload a document to an API at /document/upload This API returns a DOC ID When I make a call to /document/DOC_ID, the API responds with JSON in this structure: "errorCo ...

Angular Universal: Troubleshooting an Unrendered Route

Struggling for hours to make my site Universal and support Server Side Rendering, I came across the issue where the base route '' is not being rendered by the server. Surprisingly, all other routes are functioning properly when directly called fr ...

Angular 2: The linting error shows up as "Anticipated operands need to be of the same type or any"

So, I have this shared service file where a variable is defined like so: export class SharedService { activeModal: String; } Then, in my component file, I import the service and define it as follows: constructor(public sharedService: SharedService) ...

Assign the onClick function to the decoration of a Vscode extension

When I click on a vscode decoration, I want to trigger a function. Here's the code I created for this: const decoration = { range, hoverMessage: `${command} ${input}`, command: { title: 'Run Function', command: ' ...

Injecting a service into another service in Angular2: A comprehensive guide

Instead of reading a property 'method1' from service2, I am attempting to inject service1 into service2 as shown below: @Injectable() export class myFirstService { method1() {} } @Injectable() export class mySecondService { constructo ...

Typescript's spellbinding courses

I'm encountering some issues with Typescript and the "@botstan/Magic" library in nodejs. Before we proceed, please take a look at the "Magic" documentation. Follow these lines: import Magic from "@botstan/magic"; import * as _ from "lodash"; @ ...

What is the best way to transform my tuple so that it can be properly formatted for JSON in Python?

I have a Python code snippet that looks like this: @app.route('/getData', methods = ['GET']) def get_Data(): c.execute("SELECT abstract,category,date,url from Data") data = c.fetchall() resp = jsonify(data) resp.st ...