The Observable<Response> type cannot be assigned to an Observable<List<Todo>> type

I'm currently working on a project that is somewhat inspired by this example, but I've encountered a TypeScript error and I would appreciate some guidance on what might be causing it. As far as I can tell, I am following the correct procedures.

Below is part of the code I have written so far:

import {Injectable,Inject} from '@angular/core';
import {Http,Headers,URLSearchParams, Response} from '@angular/http';
import {List, Record} from 'immutable';
import {Observable} from "rxjs/Observable";

const TodoRecord = Record({
    id: 0,
    description: "",
    completed: false
});

export class Todo extends TodoRecord {

    id:number;
    description:string;
    completed: boolean;

    constructor(props: any) {
        super(props);
    }

}

@Injectable()

export class TodoBackendService {
    constructor(private http: Http){
        this.http = http;
    }

    getAllTodos(){
        return this.http.get("/todo");
    }

    saveTodo(newTodo: Todo): Observable<List<Todo>> {
        var headers = new Headers();
        headers.append("Content-Type", "application/json; chartset=utf-8");

        return this.http.post("/todo", JSON.stringify(newTodo.toJS()),{headers}).share();
    }
}

The line of code in Visual Studio Code that is triggering an error is:

 return this.http.post("/todo", JSON.stringify(newTodo.toJS()),{headers}).share();

And here is the error message displayed in VS Code:

https://i.sstatic.net/jQt4A.png

Any assistance or advice on resolving this issue would be greatly appreciated.

Answer №1

The meaning is clear. When making an http post, the response received is an Observable<Response>, rather than an

Observable<List<Todo>>
.

To convert the response into a List<Todo>, you will need to utilize the map() function.

Answer №2

In order to utilize the map function, it's important to understand that response.json() should yield an array of ToDo models.

storeTask(newTask: Task): Observable<List<Task>> {
    var headers = new Headers();
    headers.append("Content-Type", "application/json; chartset=utf-8");

    return this.http.post("/task", JSON.stringify(newTask.toJS()),{headers})
        .map((response: Response) => (<ToDo[]>response.json())).share();
}

Answer №3

Give this a shot...

addNewTask(todoItem: Todo) : Observable<any> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json; charset=utf-8');
        return this.http.post('/tasks',JSON.stringify(todoItem.toJS()),{headers}).share();
    }

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

When attempting to run the yarn build dist command, an error of type TypeError is encountered, stating that it is not possible to set the constructor property

Upon executing the following command in a GitHub workflow, I encountered this error: npm-run-all -p types transpile @internal_package: $ swc src --out-dir dist @internal_package: /home/runner/work/repo-name/repo-name/node_modules/ttypescript/lib/loadTypesc ...

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...

Angular2 form builder generating dynamic forms based on results of asynchronous calls

When creating my form, I encountered a challenge with passing the results of an asynchronous call to the form builder. This is what I have attempted: export class PerformInspectionPage implements OnInit { checklists: any; inspectionform: FormGroup; n ...

Adding images in real-time

I am currently working on an Angular application where I need to assign unique images to each button. Here is the HTML code snippet: <div *ngFor="let item of myItems"> <button class="custom-button"><img src="../../assets/img/flower.png ...

Optimizing media queries with Angular: A comprehensive guide

I am currently using NgZone to handle media queries in my Angular project. I am curious if there is a more efficient way to achieve this. import { NgZone } from '@angular/core'; const SMALL_WIDTH_BREAKPOINT = 840; export class AppComponent im ...

The stack property of [object Object] cannot be updated, as it only has a getter method

I can't figure out why I'm receiving this specific error in the Plunker below. Cannot set property stack of [object Object] which has only a getter Access the Plunker here: https://plnkr.co/edit/IP1ssat2Gpu1Cra495u2?p=preview The code causi ...

Methods for showcasing an angular object generated by a function

There is a function in my code that returns an object. public getLinkedTREsLevel() { let result: any; if (this.entry && this.entry.config ) { this.entry.config.forEach( element => { if (element.name === 'creationTIme') { ...

Accessing information from RESTful Web Service with Angular 2's Http functionality

I am currently working on retrieving data from a RESTful web service using Angular 2 Http. Initially, I inject the service into the constructor of the client component class: constructor (private _myService: MyService, private route: Activat ...

Transmit information between components through a form

Is there a way to transfer data from one component to another in Angular? I have two components set up and I am currently using a selector to display the HTML content in the first component. Now, I need to figure out how to send the data entered in a form ...

Issue with applying Angular animation to child element

Here I have set up two different animations. animations: [ trigger('fadeIn', [ transition('void => *', [ style({opacity: 0}), animate(500), ]), ]), trigger('fallIn',[ transition ...

What is the best way to incorporate Tradingview's JavaScript into the render function of a React Typescript

I'm trying to incorporate some widgets into my Typescript React component. Here is the embed code export default class App extends React.Component { render(): ReactNode { return ( <div> Chart test <div className= ...

Leveraging React Hooks to display a dynamic pie chart by fetching and mapping data from an API

I have a task where I need to fetch data from an API that returns an object containing two numbers and a list structured like this... {2, 1 , []} The project I'm currently working on utilizes 'use-global-hook' for managing state in Redux. T ...

When converting to a React Functional Component using Typescript, an error occurred: The property 'forceUpdateHandler' could not be found on the type 'MutableRefObject<Spinner | null>'

Looking to convert the App component in this CodePen into a Functional component using Typescript. Encountering an error when attempting to run it: ERROR in src/App.tsx:13:14 TS2339: Property 'forceUpdateHandler' does not exist on type 'Mu ...

Declarations of Typescript React for Props for Specific Element

I am trying to specify types for certain elements like <button> or <input>, but I am unable to differentiate between specific element types. Here is an example: interface Props{ component: React.ComponentProps<"button"> | nev ...

Can wildcard paths be imported in React using Typescript?

Is there a way to dynamically import a React Typescript Component from a wildcard path, similar to the following code snippet? const Component = loadable( () => import(`../../../src/**/*/${component_name}`), ); I have searched numerous solutions on ...

Attempting to fill a template using ngfor, wherein the initial 2 elements are displayed in a row

I am attempting to complete a task where, using an ngFor directive to iterate through an array, I need to display the first 2 elements in a row and the remaining elements in a descending column. It should look like this: first second third fourth fifth ...

NestJS is unable to resolve the dependencies for JWT_MODULE_OPTIONS

My compilation failed with the following error message: Nest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Please ensure that the argument at index [0] is available in the JwtModule context. +52ms I encountered similar issues regarding d ...

How is it possible that this is not causing a syntax or compile-time error?

Oops! I made a mistake and typed : instead of = on line 2 of this code snippet. Why does Typescript allow this error? Isn't colon supposed to indicate a known Type for a property declaration? I'm pretty sure there's a reason encoded in the ...

What sets apart the commands npm install --force and npm install --legacy-peer-deps from each other?

I'm encountering an issue while trying to set up node_modules for a project using npm install. Unfortunately, the process is failing. Error Log: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolv ...