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

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...

Transforming Observable into a Promise

Is it considered a best practice to convert an observable object to a promise, given that observables can be used in most scenarios instead of promises? I recently started learning Angular and came across the following code snippet in a new project using ...

Tips for retrieving an item from a (dropdown) menu in Angular

I am facing an issue with selecting objects from a dropdown list. The array called "devices" stores a list of Bluetooth devices. Here is the HTML code: <select (change)="selectDevice($event.target.data)"> <option>Select ...

Unveiling the Mystery of Angular: Why are constructor parameters without access specifiers hidden from view outside the

When I explicitly set an access specifier for a constructor parameter, it becomes visible outside the constructor. For example: constructor(private employeResourceService:EmployeeResourceService ){ //code} ngOnInit(){ this.employeResourceService=unde ...

Error: The module '@angular/localize/init' could not be located within the specified directory '/usr/src/app/src'

After upgrading from Angular 8 to 9, I added the @angular/localize package. In my polyfill.ts file, I included the following import: import '@angular/localize/init'; When I compile and run my app locally in a browser, everything works fine. How ...

Setting up Angular 6 on Azure Platform

I am currently facing challenges while trying to deploy a sample application on the azure portal. To start off, I decided to run some tests by creating an Angular app using 'ng new poc-pwa-angular-v2', and then pushed it to a Bitbucket repositor ...

What sets enum with string values apart from a string type union in TypeScript?

When it comes to defining a variable with a predefined set of values in TypeScript code, there are two approaches - using an enum or using a union. For instance, imagine we have a button with various variants such as primary, secondary, and tertiary. We ...

routerLinkActive maintains its active state even after another link has been clicked

<ul> <li routerLinkActive="active"><a routerLink="/">One</a></li> <li routerLinkActive="active"><a routerLink="/somewhere">Two</a></li> </ul> Upon clicking the link Two, both links are being hi ...

An error occurred in the ngrx store with Angular during production build: TypeError - Unable to access property 'release' of undefined

After deploying my application and running it, I encountered an issue that seems to be happening only during production build at runtime. At this point, I am uncertain whether this is a bug or if there is a mistake in my code. The error "TypeError: Cannot ...

When creating an async function, the type of return value must be the universal Promise<T> type

https://i.stack.imgur.com/MhNuX.png Can you explain why TSlint continues to show the error message "The return type of an async function or method must be the global Promise type"? I'm confused about what the issue might be. UPDATE: https://i.stac ...

Exploring Custom Scrolling Effects in Angular 2

Have you ever heard of react-router-scroll in React? It allows React app pages to scroll smoothly like a regular website. The feature scrolls to the top of each new page (route), while remembering the scroll position of previous pages. This means that when ...

Monitoring changes within the browser width with Angular 2 to automatically refresh the model

One of the challenges I faced in my Angular 2 application was implementing responsive design by adjusting styles based on browser window width. Below is a snippet of SCSS code showing how I achieved this: .content{ /*styles for narrow screens*/ @m ...

Navigating through elements in Angular

I am working with multiple Angular components housed within a display:flex div container. I am fetching datatable from an API, and it contains the same number of rows as there are components. Each row in the datatable corresponds to data for each compone ...

Ways to ensure that your Angular component.ts file is executed only after the body has completely loaded without relying on any external

I am attempting to add an event listener to an element created with a unique identifier using uuid, but I keep getting an error that states "Cannot read properties of null (reading 'addEventListener')" export class CommentItemComponent implements ...

Getting Form Value in Component.ts with Angular 5

How can I incorporate an input form into my component while constructing a form? <div class="row"> <div class="col-md-6 offset-md-3 text-center> <h2> Login Form </h2> <form (ngSubmit)="OnSubmit(login.value,password.value)" #l ...

Angular 7 implementation of the Owl carousel

Recently, I started using the Owl carousel in Angular 7. First, I installed it by running this command: npm install ngx-owl-carousel owl.carousel jquery --save I then added these scripts to my angular.json file: "scripts": ["./node_modules/jquery/dist ...

"Sorry, there was an issue with AmStockCharts when trying to update the chart: Unable to assign a value to the '

Currently, I am using Angular 4.3.6 along with TypeScript 2.4.2 for my project. The issue that I am facing involves reading data from a socket and attempting to add it to the dataprovider. I came across an example at: While implementing a serial chart, q ...

Issue with saving date values accurately in Nestjs/Prisma

After logging the response body before saving it to the database, I noticed that the shape is correct. Here's what it looks like: //console.log response body CreateOpenHourDto { day: 'WEDNESDAY', startTime: 1663858800000, endTime: 16638786 ...

What is the process for incorporating the jsnetworkx library into an ionic or angular 4 project?

When using any Ionic3 app service import * as jsnx from 'jsnetworkx'; The output error message is: Uncaught (in promise): Error: Cannot find module "lodash/lang/isPlainObject" Error: Cannot find module "lodash/lang/isPlainObject" at webpackMis ...

When reference variables are utilized before being parsed, what happens?

I'm a beginner learning Angular and have a question regarding the use of reference variables. Here is an example code snippet: <div class="bg-info text-white p-2"> Selected Product: {{product.value || '(None)'}} </div> <di ...