There seems to be an issue with the message "Property 'json' does not exist on type 'User'."

Could someone help me understand the error message I'm getting in my code below? The error says "Property 'json' does not exist on type 'User'". Here are some details about my setup:

Angular version: 12.2.12 Node: 16.13.0 Package Manager: npm 8.1.2

        // model.ts
        export class User{
        UserID : number
        UserName : string
        FirstName : string
        LastName : string
        Email : string
        Password : string
        ConfrimPass : string
        UserRole : string
        Authorize_building :string 
    }
    
    //component.ts
    resetForm(form? : NgForm) {
        if (form != null)
        form.reset();
        this.userService.selectUser = {
          UserID: null,
          UserName: '',
          FirstName: '',
          LastName: '',
          Email: '',
          Password: '',
          ConfrimPass: '',
          UserRole: '',
          Authorize_building: '',
        }
      }


     //service.ts
       PostUser(usr : User): Observable<User>{
       var body = JSON.stringify(usr);
       var headerOption = new Headers({ 'Content-Type' : 'application/json' });
       var requestOption = new RequestOPtions({ method: RequestMethod.Post, headers: headerOption });
    // return this.http.post('https://localhost:44339/api/Users', body, requestOption).map(x => x.json());
    
    var headersOption = ({ 'Content-Type' : 'application/json' });
    var body = JSON.stringify(usr);
    return this.http.post<User>('https://localhost:44339/api/Users', body, { headers: headersOption } ).map(x => x.json());
    };
  }

Please provide a solution to resolve this issue!

Answer №1

To handle this, I recommend type-asserting the Response:

For instance...

.map(x => x.json());

One approach could be

.map((x: Type) => x.json())

Answer №2

To enhance your code, consider incorporating the map function within a pipe operator as demonstrated here:

.pipe(map((result) => result.json()))

Don't forget to import both map and pipe from the RxJs library like so:

import { map, pipe } from 'rxjs/operators'

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

Searching within an Angular component's DOM using JQuery is restricted

Want to incorporate JQuery for DOM manipulation within Angular components, but only want it to target the specific markup within each component. Trying to implement Shadow DOM with this component: import { Component, OnInit, ViewEncapsulation } from &apo ...

A guide on implementing Redux Toolkit in an SPFX (typescript) project

I am currently working on developing SPFX components using typescript and webpack. My goal is to integrate redux toolkit into my project, but it is causing compilation errors. Here is what I have done so far: Created the project structure using yo Insta ...

Issue with the code: Only arrays and iterable objects are permitted in Angular 7

Trying to display some JSON data, but encountering the following error: Error Message: Error trying to diff 'Leanne Graham'. Only arrays and iterables are allowed Below is the code snippet: The Data {id: 1, name: "Leanne Graham"} app.compone ...

Provide an instance of mockClient for AWS SQSClient in a TypeScript class

I'm currently working on unit testing a piece of code that relies on a constructor with an SQSClient object for interacting with an sqs queue. To write effective unit tests, I need to mock the client so that I can test the code without actually access ...

Angular service unit test failed to execute

I have a service that I need to test, so I created a file named 'maincause.service.spec.ts' as shown below: fdescribe('MainCauseService', () => { let injector: TestBed; let service: MainCauseService; let httpMock: HttpTestin ...

Highlight the active class on the Angular Navbar

I have been successfully using [routerLinkActive]="['active']" in my application to add an active class when the button on navbar is clicked and redirects to example.com/home. However, I noticed that if I only navigate to example.com, the active ...

Encountering an error message in Ionic/Angular: "No routes found that match the URL

Encountering an issue when trying to open the detailed view from a component within my list. Currently using Ionic 4. ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'algodetail' Many discussions on this error ...

Switch the currently active tab in an Angular component using Bootstrap

I've been struggling with what seems like a simple issue for some time now. Despite searching through various Stack Overflow solutions, I can't seem to find one that fits my specific use case... The problem I'm facing involves an angular co ...

Having trouble retrieving JSON data from a Node.js server and displaying it on an Ionic page - encountering an issue with finding a compatible object of type 'object' that supports it

GET Response: Welcome! home.ts:44:8 POST Response: Object { passed:true, message: "sdf" } home.ts:38:10 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to ...

What is the evaluation process for conditions like someItem?.someField==somevalue in Angular?

Let's consider a simple condition in the markup: someItem?.someField==somevalue What does this mean? Is it equivalent to someItem!=null && someItem!=undefined && someItem==somevalue So essentially, if someItem is undefined, the ent ...

Discovering GraphQl errors within a React component or custom hook is a crucial skill to master

Currently using @apollo/client and everything seems to be functioning properly. Within my index.ts file, I am logging any Graphql errors that occur const errorLink = onError(({ graphQLErrors, networkError }) => { if (graphQLErrors) { graphQLErrors.map(( ...

Guide to establishing and maintaining an observable that relies on an @Input variable

In a basic component, there is an input called criteria and an observable named result$. class Foo { @Input() private criteria: string; private result$: Observable<any>; constructor(private service: MyService) { } } The class MyService ha ...

Circular dependency in typescript caused by decorator circular reference

Dealing with a circular dependency issue in my decorators, where the class ThingA has a relation with ThingB and vice versa is causing problems for me. I've looked into various solutions that others have proposed: Beautiful fix for circular depende ...

Assessing asynchronous HTTP function with Jamine: Exceeding time limit - No response received within 5000ms

ISSUE: Dealing with asynchronous functions returning Promises that rely on nested HTTP calls. USED TECHNOLOGIES: Angular 9, Jasmine 3.4.0 ERROR ENCOUNTERED: Error: Timeout - Async callback was not invoked within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INT ...

Combining Two Dropdown Selections to Create a Unique Name using Angular

I am facing a challenge with 2 dropdown values and input fields, where I want to combine the selected values from the dropdowns into the input field. Below is the HTML code snippet: <div class="form-group"> <label>{{l("RoomType")}}</labe ...

Exploring Typescript Decorators: Extracting the Type of a Property

When working with data from Strapi, I have developed a process of simplifying the flow by converting it using interfaces and then converting it back to its original Strapi format. Essentially, this means taking data in one format and transforming it into a ...

Is it feasible to link an Angular property value to the value of an HTML data attribute?

Can an Angular property value be bound to a data attribute on a template element? <h1 data-name="{{name}}">Hello from {{ name }}!</h1> Example Link After running the code, it results in the following error: Error in src/main.ts (11: ...

Is there a problem with ngModel while working with dynamically changing data?

I've been working on creating a custom datatable with Angular 4 CLI and JSON arrays. Successfully, I have managed to build a table with dynamic columns and rows. Now, my focus is on implementing a column filter using a dropdown checkbox style. Below i ...

Transferring Information in Angular 8 between components on the Same Level

Currently utilizing Angular 8 with two independent components. One component contains a form with an ID field, and the other is accessed by clicking a button from the first component. The second component does not display simultaneously with the first. A ...

Difficulty with Mobx observables and componentDidUpdate() in Typescript React when passing props may lead to unexpected behavior

I am currently working with react, mobx, and typescript and I am facing an issue while trying to send a json array from my logic layer to a UI component. The json data is fetched from an async API call and then stored in an observable variable using mobx. ...