Unable to associate Interface with HTTP response

When I run the following code in Chrome console, I get an error:

ERROR TypeError: t.json(...).map is not a function
. However, both ng serve -prod and ng test --sm=false work fine.

My goal is to map the result to the model in Interface and display it in HTML.

....
export interface UsersData {
   _id: number;
   email: string;
   fullName: string;
}
export class RetrieveUsrData {
    private issuesUrl = 'http://localhost:4000/users';
    getUserDetails(): Observable<UsersData[]> {
      return this.http.get(this.issuesUrl)
                      .map(this.extractData)
    }

    extractData(result: Response): UsersData[] {
        console.log(JSON.stringify( result.json()) );
        return result.json().map(usr => {
            return {
                _id: usr.message._id,
                email: usr.message.email,
                fullName: usr.message.fullName
            }
        }).subscribe(result => result = result);
    }
    constructor(private http: Http) {}
}
...

I have been looking into various issues such as mapping a HTTP response to a JSON and then mapping the JSON to a model, and made adjustments to my code/method like so:

extractData(result: Response): UsersData[] {
    return result.json().map(res => ({
        _id:res.message._id,
        email:res.message.email,
        fullName:res.message.fullName
    }) as UsersData)
    .subscribe(result => result = result); ;
}

Despite these changes, I am still encountering the same error.

Answer №1

The method called .map can only be used with arrays, not objects.

If you are encountering an error, it is likely due to having a response similar to this:

{
    someKey: [1, 2, 3, 4]
}

To resolve this issue, you should use the following code:

result.json().someKey.map( //...

In some cases, you may even simplify things by using the following line if the JSON data follows your interface correctly:

return <UsersData[]>result.json().someKey;

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

The Mongoose getter function is triggering error TS2590 by generating a union type that is too intricate to be displayed

I've come across the TS2590: Expression produces a union type that is too complex to represent error while trying to compile TypeScript. The issue seems to be connected to the id's getter function idFromString, as removing the id getter prevents ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

The 'undefined' type cannot be assigned to the 'never' type

interface A { name?: string age: number } var a: A = { name: '', age: 23 } var result:A = (Object.keys(a) as Array<keyof A>).reduce((prev, key) => { if (a[key] || a[key] === 0) { prev[key] = a[key] // an error was reporte ...

Using Angular, Typescript, and ngxs to manage state observables, one may wonder what exactly a variable ending with an exclamation mark (!) signifies. An example of this can be seen in the following code snippet:

Within my TS file, a declaration is present: import { Select } from '@ngxs/store'; @Injectable() export class someService { @Select(someSELECTOR) varName$!: Observable<someType[]>; elements$ = this.varName$.pipe( map(elements => e ...

Website API: decouple backend and frontend functionality through an API

I am currently working on the development of a website and an app created through Cordova. The app will essentially mirror the functionalities of the website. The website is already established and heavily relies on JavaScript, with potential considerati ...

The change in $stateparams is not being reflected in the services, even when it is updated outside the factory

var routerApp = angular.module('routerApp', ['ui.router','ngResource']); routerApp.config(function($stateProvider, $urlRouterProvider) { $stateProvider // HOME STATES AND NESTED VIEWS .state('partyDeta ...

Can someone explain what logForm.$invalid.$setValidity is all about?

The code snippet can be found here I am a beginner in this field and currently studying a piece of code. I am having trouble understanding the logForm.$invalid.$setValidity line. I have searched online but couldn't find any information about it. The ...

What could be causing the AngularUI bootstrap datepicker to not appear?

Exploring the popup datepicker demo from angularUI bootstrap, which is embedded in their page and works perfectly. However, when I tried to create a minimal plunker here, the button click does not open the calendar. Any thoughts on what might be causing th ...

After AngularJS has loaded, CSS animations seem to be ineffective

When loading a page, I have created a div that is displayed. Here is the code: <div ng-show="load" class="rb-animate-time rb-animate-hide rb-load"> <div class="text">Hello world</div> </div> <div ng-init="load = false">&l ...

Issue with angular ui-router transition override/intercepted/disrupted/terminated

Encountering these errors: Error: transition superseded at $StateProvider.$get (http://localhost:1337/angular-ui-router/release/angular-ui-router.js:2903:42) Error: transition prevented Error: transition aborted Error: transition failed After researc ...

Error message in Ionic 2: "Property is not found on type"

Currently, I am working on a project in Ionic 2 and have encountered a stumbling block with a seemingly simple task. My issue lies with a Textbox where I aim to input text that will then be displayed. I found some code on a website (http://www.tizag.com/j ...

Need for utilizing a decorator when implementing an interface

I am interested in implementing a rule that mandates certain members of a typescript interface to have decorators in their implementation. Below is an example of the interface I have: export interface InjectComponentDef<TComponent> { // TODO: How ...

Exploring Angular 1.5: A guide to binding a transcluded template to a component's scope

Currently, I am utilizing a form component that includes common validation and saving functions. Inputs are injected into the form as transcluded templates in the following manner: <form-editor entity="vm.entity"> <input ng-model="vm.dirt ...

Experiencing difficulties retrieving information from the database through the use of AngularJS and PHP

I am currently working on retrieving data from a MySQL database using PHP and displaying it with AngularJS. Unfortunately, I encountered an error message in the browser's console that is preventing me from successfully fetching the data. response < ...

Verify the dimensions of the file being uploaded

I have a file uploader component that requires a dimensions validator to be added. Below is the code for the validator: export const filesDimensionValidator = (maxWidth: number, maxHeight: number): ValidatorFn => (control: AbstractControl): Vali ...

What is the process for setting the active state for HtmlBodyElement?

I attempted to use the following method: document.querySelector('body').setActive(); However, I encountered an error: TS2339: Property 'setActive' does not exist on type 'HTMLBodyElement'. Any suggestions on how to resolve t ...

Enhance user interaction in Angular 13 by animating a selected element using just one animation block

I am currently working on a one-page website project to enhance my Angular skills, and I'm facing a challenge with animating multiple DOM elements using a single animation. Defining the animation for each element individually seems like a cumbersome a ...

Ways to control the number of function invocations in an AngularJS controller

I am facing a challenge where data is being fetched from multiple controllers, causing functions to hit the server more than fifty times until they receive a response. I am unsure how to handle this situation effectively and would appreciate some guidance. ...

My goal is to prevent users from using the Backspace key within the input field

Let's say we want to prevent users from using the backspace key on an input field in this scenario. In our template, we pass the $event like so: <input (input)="onInput($event)"> Meanwhile, in our app.component.ts file, the function ...

The text input is malfunctioning in the IE web browser

For my project, I am incorporating AngularJS but encountering an issue with the input type text in IE browsers specifically IE 11 and IE 10. The problem arises when clicking on the input box - while the focus is triggered, the cursor does not appear insid ...