Receiving feedback from an http.post request and transferring it to the component.ts file in an Angular

Currently, I am facing an issue with passing the response from an http.post call in my TypeScript service component to an Angular 2 component for display on the frontend. Below are the code structures of my service.ts and component.ts:

getSearchProfileResponse(body) {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this._url, body, options)
      .map((response:Response) => {
        console.log(JSON.stringify(response));
        JSON.stringify(response);
      })
      .catch((error) => {
        console.log("error is "+ error);
        return Observable.throw(error);
      });
  }

getProfile() {
    this.spinnerService.show();
    this.searchProfileRequest = _.cloneDeep(this.searchKey);
    this.searchProfileService.getSearchProfileResponse(this.searchProfileRequest)
      .subscribe(
        searchProfileResponse => {
          this.searchResult = searchProfileResponse;
          console.log("response in component is "+ searchProfileResponse);  // this is displayed as undefined
          console.log("search result is "+ this.searchResult);
          this.spinnerService.hide();
          this.showProfiles(this.searchResult);
        },
        error => {
          console.log(error);
          this.spinnerService.hide();
          this.showError();
        }
      );
  }

I have noticed that data is being passed correctly in the response within the getSearchProfileResponse(body) method. However, in the getProfile() method's response, it appears as "undefined". Any help or suggestions would be greatly appreciated!

Answer №1

Don't forget to include the return statement in your .map() function.

Check out the revised code below:

getSearchProfileResponse(body) {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this._url, body, options)
      .map((response:Response) => {
        console.log(JSON.stringify(response));
        return JSON.stringify(response);
      })
      .catch((error) => {
        console.log("An error occurred: "+ error);
        return Observable.throw(error);
      });
  }

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

An error occurred in TypeScript when trying to use the useState function with a string type. The ReferenceError indicates that

import React, { FunctionComponent, useState, useEffect } from 'react' const SearchBar: FunctionComponent = () => { const [searchValue, setSearchValue] = useState<string>('') const [isSuggestionOpen, setIsSuggestionO ...

What is the best approach to creating multiple dropdowns in ant-design with unique options for each?

It seems like I may be overlooking a simple solution here. Ant-Design dropdowns utilize an array of ItemProp objects to show the options, but this restricts me to having only one list of options. const choices: MenuProps['items'] = [ { label: ...

What is the process for uploading this JSON data to Firestore and performing queries on it?

Can someone please guide me on how to push the following JSON data into firestore using Angular? var customer = { "name": "john", "address": "xxxxx", "order": { "bookList": [{ "quantity": "3", "price": ...

The pipe operator in Angular is failing to function as intended

I encountered an error while using the replace operator in Angular. Can someone help me identify the issue? Check out this link for more information ...

Exploring the World of Angular6 with the Incredible Power of tinyMCE Editor

Hello, I'm looking to incorporate the tinyMCE editor into my Angular 6 application. I followed a thread that explains how to integrate it, but I ran into an issue where it says the domain is not registered. I would prefer to do this without requiring ...

Having trouble triggering a dot MVC controller action method from an Angular service

Encountering the following Error: CORS policy block: Preflight request response access control check fails with HTTP ok status missing. Note: The ajax call successfully triggers the action method in other web applications, but an error is raised when usin ...

What is the process for obtaining an app icon from the store using Angular?

Currently, I am working on an app using ionic, angular, and Cordova. Within this app, there are links to other apps available in the app store. My main query is: Is there a way to retrieve the icons of these apps from the store? I aim to display these ic ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...

Angular2: Dynamically switch between selected checkboxes in a list

Is there a way to toggle a checked checkbox list in Angular2? I am trying to create a button that, when pressed while the full list is visible, will display only the checked items. Pressing the button again would show the entire list. Here's the Plu ...

Executing a method during the initialization process in app.component.ts

One thing I've noticed is that the <app-root> component in Angular doesn't implement OnInit like all the other components. It may sound silly, but let's say I wanted to add a simple console.log('Hello World') statement to dis ...

Issue encountered while attempting to utilize a basic redux reducer to define a boolean value, regarding a mismatch in overrides

Currently, I am working on a project to enhance my understanding of Redux and Typescript. I am still navigating through the learning curve in this area. Based on what I have learned from a book, I have established a "slice" that includes definitions for r ...

Utilizing getter and setter functions within a setter with a type guard

I need to implement a getter and setter in my class. The setter should accept a querySelector, while the getter is expected to return a new type called pageSections. The challenge I'm facing is that both the getter and setter must have the same argum ...

the ngbPopover refuses to appear

I'm attempting to utilize the popover feature from ng-bootstrap in my Angular2/Typescript application, following the guidelines at here. Despite not encountering any errors, I am facing an issue where the popover does not appear. Here is the snippet ...

Can an L1 VPC (CfnVpc) be transformed into an L2 VPC (IVpc)?

Due to the significant limitations of the Vpc construct, our team had to make a switch in our code to utilize CfnVpc in order to avoid having to dismantle the VPC every time we add or remove subnets. This transition has brought about various challenges... ...

Using a dictionary of class types as input and returning a dictionary of their corresponding instances

Is there a way to create a function that takes a dictionary with class values as an argument and returns a dictionary of their instances? For example: classes C1, C2 function f: ({ name1: C1, name2: C2 }): ({ name1: new C1() name2: new C2 ...

Challenge encountered with asynchronous angular queries

Dealing with asynchronous calls in Angular can be tricky. One common issue is getting an array as undefined due to the asynchronous nature of the calls. How can this be solved? private fetchData(id){ var array = []; this.httpClient.get('someUrl ...

Setting up an Angular proxy for Server prod: A step-by-step guide

Exploring a new approach in my Angular front end app, I aim to conceal the API URL from the browser's network. For example, instead of directly calling api.url.dz/login, I wish to call front.url.dz/login on the front end and then redirect it to api.ur ...

Updating the variable value within the Highcharts selection event using Angular

Here is an angular 7+ code snippet using the Highcharts API: export class TestComponent implements OnInit{ seek: boolean = false; exampleChart; public options = { chart:{ zoomType: 'x', events: { ...

The element's 'nativeElement' property cannot be accessed because it is undefined

I have a scenario where I have a parent component and a child component. I am trying to access the DOM element of the Child component from the Parent component, but I keep encountering an issue with the native element being undefined. export class ChildCom ...

Transferring information through parent-child components via onChange

I have a question regarding data binding. In my project, I have a parent component and two child components: Parent: directives: [firstChild,secondChild], template:' <first-child [showList]="showList" (emitShowList)="getShowList($event)"& ...