Issue TS2322: Type 'Observable<string[]>' is not compatible with type 'Observable<Sensors[]>'

This issue:

error TS2322: The type 'Observable' cannot be assigned to the type 'Observable'. The type 'string[]' cannot be assigned to the type 'Sensors[]'. The type 'string' cannot be assigned to the type 'Sensors'.

arises from this TypeScript snippet:

    import { Observable } from 'rxjs/Rx';
    import { map, startWith } from 'rxjs/operators';

    filteredSensors: Observable<Sensors[]>;

        constructor(private fb: FormBuilder, private ws: SensorService
            ) {
                this.myform= new FormGroup({
                  'sensors_id': this.fb.array([], Validators.required),
                  'unit_price': new FormControl('', [Validators.required, Validators.nullValidator]),
                });

                    this.filteredSensors = this.myform.controls['sensors_id'].valueChanges
                  .pipe(
                    startWith(['']),
                  );
              }
        ngOnInit() {
           this.ws.getAllSensors().subscribe(
            sensors => {
            this.sensors = sensors
           }
         );
       }

The HTML section includes:

*ngFor="let sensor of filteredSensors | async | myPipe: sensors : 'sensor_serial': i"

Also, a custom pipe is utilized as shown below:

    import { Pipe, PipeTransform } from '@angular/core';

    @Pipe({
        name: 'myPipe'
    })
 export class MyPipe implements PipeTransform {
    transform<T>(value: Sensors, list: T[], field: string, idx: number): T[] {
        const filterValue = value[idx] ? value[idx].toString().toLowerCase() : ''; //correct this line of as per Sensors object
        return list.filter(sensor => sensor[field].toLowerCase().indexOf(filterValue) === 0);
    }
}

Any suggestions on resolving this error?

Sensors.ts

export class Sensors {
    sensorType_id: number;
    sensortype_id: number;
    sensors_id: string;
    sensor_serial: string;
    active: number;
    sensordescription: string;
    unit_price: number;
    description: string;
    note: string;
    Sensor_id: number;
    default_price: number;
    client_id: string;
    client_name: String;

    constructor(obj: any) {

        this.sensorType_id = obj && obj.sensortype_id || obj.sensorType_id;
        this.sensortype_id = obj && obj.sensortype_id;
        this.client_id = obj && obj.client_id;
        this.sensor_serial = obj && obj.sensor_serial;
        this.sensors_id = obj && obj.sensors_id;
        this.active = obj && obj.active;
        this.sensordescription = obj && obj.sensordescription;
        this.unit_price = obj && obj.unit_price;
        this.description = obj && obj.description;
        this.note = obj && obj.note;
        this.Sensor_id = obj && obj.Sensor_id;
        this.default_price = obj && obj.default_price;
        this.client_name = obj && obj.client_name;
    }
}

and the SensorService (ws):

public getAllSensors(): Observable<Sensors[]> {
    let headers = new Headers();
    headers.append('x-access-token', this.auth.getCurrentUser().token);
    return this.http.get(Api.getUrl(Api.URLS.getAllSensors), {
        headers: headers
    })
        .map((response: Response) => {
            let res = response.json();
            if (res.StatusCode === 1) {
                this.auth.logout();
                return false;
            } else {
                return res.StatusDescription.map(sensors => {
                    return new Sensors(sensors);
                });
            }
        });
}

Answer №1

There seems to be a type mismatch in your Pipe. Your Pipe is supposed to work with String, but you are passing Sensors instead. To fix this, update the argument type of your Pipe and adjust the business logic inside the Pipe.

 @Pipe({
  name: 'myPipe'
})
export class MyPipe implements PipeTransform {
  transform(items: string[], value: string): any[] {
    if (!items) {
      return [];
    }
    let array =  items.filter(item => item == value);
    return  items.filter(item => item == value);
  }
}

in HTML

*ngFor="let sensor of filteredSensors | async | myPipe: i"

Note: 'i' mentioned here represents the value used for filtering.

You can see a working example here - https://stackblitz.com/edit/angular-pipe-on-array

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

Making a synchronous call to a web API using JQuery

Understanding JQuery promises and deferred objects has been a bit of a challenge for me, so please bear with me. I should also mention that my application is built using React, Typescript, and ES6. Let's imagine we have an array of objects: [{ Objec ...

Angular Signal computation does not initiate a re-render

I am currently working on sorting an array of signals within my component. To achieve this, I have wrapped the array in a compute function that sorts it. Below is the relevant code snippet: In the Service file: private readonly _lobbies = signal<Lobby ...

The component 'Form' cannot be utilized in JSX because its return type, 'ReactNode', is not a valid JSX element

I'm facing an issue with my Next.js application written in TypeScript after updating react-bootstrap. After the update, I am encountering the following error when attempting to use the Form component from react-bootstrap: react-bootstrap: ^2.10.3 @typ ...

Angular Application caught in an infinite loop

Currently, I have an Angular web application that utilizes the @microsoft/microsoft-graph-client to fetch the logged-in user's details. The user is signed in using @azure/msal-angular. In order to log the user in, I have an authentication service that ...

What is the best way to integrate Angular 4 into an AngularJS application using SystemJS?

I am looking to upgrade my AngularJS application to Angular 4. Currently, I am going through the official documentation for upgrading from AngularJS which can be found at https://angular.io/guide/upgrade. The guide mentions: In order to start converting ...

After integrating React Query into my project, all my content vanishes mysteriously

Currently, I am utilizing TypeScript and React in my project with the goal of fetching data from an API. To achieve this, I decided to incorporate React Query into the mix. import "./App.css"; import Nav from "./components/Navbar"; impo ...

Here is a way to trigger a function when a select option is changed, passing the selected option as a parameter to the function

Is there a way to call a function with specific parameters when the value of a select element changes in Angular? <div class="col-sm-6 col-md-4"> <label class="mobileNumberLabel " for="mobilrNumber">Select Service</label> <div cla ...

Using camel case, format the data in json using gRPC

I have a json data from gRPC that is in Pascal case and I need to convert it to camel case. I am using angular to interact with the gRPC service. However, despite serializing and converting the result to camel case, the output in angular always remains in ...

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...

What is the proper way to utilize ngIfElse in Angular 9?

Currently, I have a list of posts that are being fetched using services and displayed on the UI. There is a search box with an ID field specified in it. My goal is to render the post in a card if the provided ID exists. This functionality is working well. ...

The latest alpha version of Angular2 Material Design (alpha.9-3) encountered a "404 not found" error when trying to access @angular

After carefully following the steps outlined in the angular material2 Getting Started guide to install @angular/material, I made updates to package.json, app.module, and systemjs.config using Atom. Specifically, I added the line '@angular/material&apo ...

Mastering the nesting of keys in Typescript.Unlock the secrets of

I encountered a situation where the following code snippet was causing an issue: class Transform<T> { constructor(private value: T) {} } class Test<T extends object> { constructor(private a: T) {} transform(): { [K in keyof T]: Transfo ...

utilize Java version specifically designed for integrating with Angular framework and SOAP web services

One question I've been pondering: we currently have a project built on Java 6 and GWT, but we're considering migrating to Angular (using SOAP web services). Will Java 6 be compatible with Angular for the backend, or will we need to upgrade to Jav ...

What steps should be taken to rectify the issue in the Angular HttpClient concerning the delete method?

(English is not my first language so please forgive me) Hello, I am new to Angular and I am attempting to make an HTTP request that deletes a doctor when a button is clicked. However, I am struggling with what steps I need to take to get my code working pr ...

Executing a single insert statement in a TypeScript Express application using PostgreSQL is taking over 240 milliseconds to complete

Seeking assistance with optimizing a db insert operation test using mocha for a node.js express app that utilizes fp-ts and pg npm package. The tests run successfully, but the insert test is taking over 240 ms to complete. The database table has a maximum ...

Design an element that stretches across two navigation bars

Currently, I have implemented two Navbars on my website as shown in the image below: https://i.stack.imgur.com/4QmyW.png I am now looking to include a banner that clearly indicates that this site is a test site. In addition, I would like to incorporate a ...

Mastering mapped types to replace properties in Typescript

I have created a Factory function where it takes an object as input and if that object contains specific properties, the factory transforms those properties into methods. How can I utilize mapped Types to accurately represent the type of the resulting obj ...

The risk of a race condition could arise when working with nested switchMaps in ngr

I am currently working on an Angular 9 application that heavily relies on observables. In a specific component, I have the following requirements: Retrieve all companies to access certain information. Fetch all responses and link additional company detai ...

What sets aws-cdk-lib apart from @aws-cdk/core, @aws-cdk/aws-iam, and others?

There seems to be a variety of examples out there using the AWS CDK, with some referencing aws-cdk-lib and others using @aws-cdk/core. Can someone clarify the distinction between these two and provide guidance on when to use one over the other? ...

Incorporating Ionic Elements

I've been attempting to set a default segment as active in my app. After looking through other threads and questions, the solution appears to involve making changes in the segment js file located in the components folder. However, I can't seem t ...