What to do when Angular2 HTTP request does not return any data?

I have successfully set up a backend API, and I can confirm that it is functioning properly based on the POSTMAN screenshot provided https://i.sstatic.net/pIl4k.png

Below is a snippet of my service code:

getComments(line: string, department: string, startTime?: number, endTime?: number): Observable<Array<IComments>> {
    let headers = new Headers(
        {
            'Content-Type': 'application/x-www-form-urlencoded',
            'line': line,
            'cell': department,
            'start': new Date(),
            'end': ago(24, "hours")
        });
    let options = new RequestOptions({ headers: headers });
    return this.http.get('api/data/comments', options)
        .map(this.extractData)
        .catch(this.handleError);
}
private extractData(res: Response) {
    let body = res.json();
    return body.data || {};
}

Furthermore, here is an excerpt from my component:

  this.dataService.getComments('604', 'powders').forEach(result => {
      console.log('Res: ' + JSON.stringify(result));
      that.comments = result;
  });

Despite having implemented the above code, the console output only shows:

Res: {}

This discrepancy raises the question as to why the expected data is not being returned in the same manner as shown in postman.

Update:

Upon adding console.log(body) within the extractData function, I received the following output:

Object {result: "COMMENTS604"}

Answer №1

Within the function extractData, you are currently returning body.data. However, considering that the property is actually labeled as result, it seems like what you intended to do was return body.result

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

Utilize the routerLink within a string value on a HashMap instance

I am currently storing translated parameters in a HashMap object on my component. However, I am facing an issue where certain attributes such as [routerLink] are not functioning properly or not being interpreted by Angular (v5). Here is the code snippet f ...

Developing Angular modules in conjunction with the primary application

What if I wanted my main web application and my mobile (ionic) application to share the same ngrx/store? I managed to separate the ngrx/store into its own module, which we can now easily include in our projects using npm. However, a downside of this is t ...

Strange occurrences with Typescript compiler when interface doesn't align

There's something strange happening with the Typescript compiler when I use an interface in certain cases. For instance, everything works perfectly fine here with no errors: interface Bar { letter: 'a' | 'b'; } declare class F ...

Update the data and paginator status

In my development project, I have implemented PrimeNG Turbotable with the code <p-table #dt. Based on information from here, using dt.reset() will clear the sort, filter, and paginator settings. However, I am looking for a solution to only reset the pa ...

Premature conclusion of observable

I'm facing an issue with an element using the async pipe to subscribe to a Behavior Subject. showDiv$ = new BehaviorSubject<boolean>(false); showDivObv$ = this.showDiv$.asObservable().pipe( tap(() => console.log('here')), ...

Issue with connecting React Router v4 to Redux - dispatch function not being properly passed

Recently, I've been working on migrating my app to React Router v4 and encountered some challenges due to the significant changes in the API. Here's where I currently stand: Setting Up the Router const createStoreWithMiddleware = applyMiddlewar ...

Removing an image from the files array in Angular 4: A step-by-step guide

I have recently started working with typescript and I am facing a challenge. I need to remove a specific image from the selected image files array before sending it to an API. app.component.html <div class="row"> <div class="col-sm-4" *ngFor ...

The issue arises when attempting to use the search feature in Ionic because friend.toLowerCase is not a valid function

I keep encountering an error message that says "friend.toLowerCase" is not a function when I use Ionic's search function. The unique aspect of my program is that instead of just a list of JSON items, I have a list with 5 properties per item, such as f ...

Issue with running ng serve command with proxyconfig.json file is unresolved

I am currently in the process of developing an application using the MEAN stack. Part of my strategy involves utilizing a Proxy config file to facilitate communication with the backend, which is developed in Node JS. proxyconfig.json { "/api/*": { ...

Leveraging GetServerSideProps for Dynamic URL Query Parameters

While working on querying the parameter in the URL within getServerSideProps, I encountered an error where ID was undefined in the DetailThemepage function. My Next.js version is V.13 and the directory structure is app/detail/[id]/page.tsx. http://loca ...

Guide to releasing your Angular 6 library to npmjs along with a detailed README.md

I'm currently in the process of developing an Angular 6 library that I intend to share on npmjs. The library, named ng-as-multiselect-dropdown, is versioned on GitHub through the workspace project 'sample'. I used the Angular-CLI command &ap ...

Should I use Mongoose Schemas to enhance the Document class or & Document?

Currently, I'm working with NestJS to develop backend code and retrieve objects from MongoDB. In their guide, they showcase examples that involve creating a class with the @Schema() annotation and then combining it with their pre-built mongoose Docume ...

Exploring Cross-Origin Resource Sharing in ASP.NET Core 2.1 and Angular: A Comprehensive Guide

There has been an abundance of discussions surrounding this topic, but I've yet to find a solution that works for me. My setup includes an asp.net core API 2.1 with an Angular 7 app. Error: "fleet:1 Access to XMLHttpRequest at 'https://loca ...

pressing buttons on user interfaces nested two levels deep

There is a 3rd party library (which cannot be altered) with the following interface: interface MyInterface { x: { a: 1, b: 2, c: 3, }, y: { d: 4, e: 5, f: 6, }, z: { g: 7, ...

Build encountered an error: module exported a null value unexpectedly

Encountering an error message while running the Angular Build (ng build --prod): ERROR in: Unexpected value 'null' exported by the module 'SharedModule' @NgModule({ declarations: [InputComponent, InputSimpleComponent, ModelEditComp ...

I am struggling with setting the data received from the backend to an array variable in Angular

Looking for assistance with my interface and service files: [Click here to view the service file code image](https://i.sstatic.net/2f0bzkDM.png) Upon executing the request to retrieve data from the backend and assign it to the variable 'users', ...

Is there a way for me to display an http status code in my fetch error?

I created a React component where I am currently working on setting the state by making a network call. My goal is to eventually pass this state down to other child components, but for now, I am focused on getting everything connected properly. While atte ...

How to utilize the CSS hover feature within an Angular directive?

Presented here is the default directive. import { Directive, Input, Renderer2, ElementRef } from '@angular/core'; @Directive({ selector: '[newBox]' }) export class BoxDirective { @Input() backgroundColor = '#fff'; con ...

Converting a string value into an object in Javascript using a command that functions similarly to eval in Python

When working with Python, the stringValue variable is often assigned as a string: stringValue = '{"DATA":{"VERSION":1.1, "STATE":True, "STATUS":"ONLINE"}}' To convert this string into a Python di ...

Getting a file object with v-file-input in Nuxt.js

For my Nuxt.Js apps, I utilized Vuetify.js as the UI framework. In order to obtain the file object when uploading files, I incorporated the v-file-input component from Vuetify.js and wrote the following code snippet: <template> <div> ...