Encountering a Problem with HTTP Requests in Angular 2

Seeking assistance with a technical issue.

My objective: Make a REST API call to retrieve JSON data and resolve an Angular 2 promise.

ServerAPI built with Node.js/ExpressJS/Lodash

Sample of server.js file:

var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var data = require('./data.json');
var _ = require('lodash');
var cors = require('cors');


app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());


app.get('/GetData', function (req, resp) {

if (req.query.search != null) {

    var result = _.find(data, function (o) {
        return o.value === req.query.search.toLowerCase().trim()
    });

    return resp.send(result)

} 

});

app.listen(1337, function () {
console.log('Listening at Port 1337'); 
}); 

Tested by running http://localhost:1337/GetData?search=colorado and successfully returning valid JSON object.

ClientAPI

Service file implementing HTTP request:

import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {Config} from "../config";
import {SearchResult} from "../models/search-result.model";
import {MockSearchData} from "../mock/mock-search-results";
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';


@Injectable()
export class ApiDataService {

constructor(private http:Http) {
}

public performSearchRequest(searchTerm:string,queryType:string):Promise<SearchResult[]> {
return new Promise<SearchResult[]>((resolve, reject) => {

let url = Config.apiBaseUrl + Config.searchApi;
url += "?search=" + searchTerm;

console.log("Your query will be sent to: " + url);

if (searchTerm != "") {

if (queryType == 'mock') {

resolve(MockSearchData);


} else if (queryType == 'api') {

let data = [];

this.http.get(url)
.map(resp => resp.json())
.subscribe(getData => data = getData);

resolve(data);

} else {

reject("No matching query type found.");

}

} else {

reject("Please provide a search term.");

};

});
}
}

The resolution of mock data, retrieved locally within the ClientAPI, is functioning as expected. However, I am facing challenges in making the api query type work properly.

The Angular application initializes without errors and executes the http.get method smoothly. Upon checking the network tab in the developer tools, it confirms that an HTTP request was made and returned the desired valid JSON response. Despite this, the table where the data should be displayed remains empty.

What could be causing this issue?

Answer №1

The problem arises at this point:

this.http.get(url)
   .map(resp => resp.json())
   .subscribe(getData => data = getData);

resolve(data);

You are subscribing to the observable, but it hasn't finished yet when you call resolve immediately afterwards. This means you are essentially just calling resolve([]).

Instead, consider something like this:

this.http.get()./*...*/.subscribe(result => resolve(result));

You may also want to explore the toPromise method on Observables as well as how to create a resolved promise directly.

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

Choose carefully when to utilize forkJoin

In a particular scenario, I need an application to generate menus based on specific contexts. Here are the definitions for menuA and menuB: // menuA example from a given source menuA() { return [ { a: 'demo1', b: &apo ...

Utilizing JSON with Express version 4.11 and the bodyParser middleware

I've been trying to figure this out for hours, searching through Stackoverflow and the internet in general. I've attempted different solutions but still can't seem to get it right. As a newcomer to node.js, I managed to follow a tutorial to ...

Creating an HTTP gateway with Observables

When dealing with multiple requests, I need to pause them until the authentication of the http request has been confirmed. Essentially, I require an http gate where some requests can pass without authentication, while others need to wait for the token to b ...

What are the recommended TypeScript tsconfig configurations for running Node.js 10?

Can someone provide information on the necessary target/libs for enabling Node.js v10.x to utilize async/await without generators? I have found plenty of resources for node 8 but not as much for node 10. ...

Express js and bodyParser combined offer a secure file uploader for enhanced data protection

After extensive searching, I found a solution to secure file uploading in express js. Here is the code that I developed: app.use(express.json()); app.use(express.urlencoded()); app.post('/',express.bodyParser({ kee ...

What could be causing the malfunction in my deleteMessage feature?

Utilizing Postman, I am simulating the deletion of data from my JSON database by sending a DELETE request via http://localhost:3001/delete/1 in the file backend/lib/routes.js import { Router } from 'express'; const messageApp = require('./co ...

Typescript mistakenly infers the wrong type: TS2339 error - it says that property 'selected' is not found on type 'string'

When examining the code snippet below, Typescript initially infers a type string for the inner element type of the values array. However, it subsequently raises an error indicating that string does not have the property "selected". let item = { values: [{ ...

Typescript not being transpiled by Webpack

As I set out to create a basic website, I opted to utilize webpack for packaging. TypeScript and SASS were my choice of tools due to their familiarity from daily use. Following the documentation at https://webpack.js.org, I encountered issues with loaders ...

Is Axios the sole option for API calls when utilizing Next.js with SSG and SSR?

Can someone clarify the best practice for data fetching in Next.js? Should we avoid using axios or other methods in our functional components, and instead rely on SSG/SSR functions? I'm new to Next.js and seeking guidance. ...

Having difficulty in sending emails through Nodemailer using a Google App Password

I implemented a route in an API that involves sending an email to users upon signing up. Utilizing nodemailer and a Google App password, everything was running smoothly until February 3rd, 2023 when the connection suddenly ceased without any changes to the ...

Is there a way to retrieve all active HTTP connections on my Express.js server?

In my express server app, I am implementing SSE (server send events) to inform clients about certain events. Below is the code snippet from my server: sseRouter.get("/stream", (req, res) => { sse.init(req, res); }); let streamCount = 0; class SS ...

Adding an icon to the contents of a specific column in Angular material

Struggling to figure out how to incorporate an icon into the data in the Status column using Angular material. Here is the markup of my page: <table mat-table [dataSource]="dataSource"> <ng-container *ngFor="let ...

Utilizing Ephemeral and MaxAge parameters in express-session for enhanced session management

I'm working on implementing the session management for an express-js application using the express-session package. Here are the specific requirements I need to meet: The cookie should be destroyed when the browser is closed. The cookie should expi ...

Attempting to publish and install a unique angular2 component using NPM and Angular-CLI results in successful compilation only on the initial try

I am facing a peculiar and frustrating issue. The problem revolves around an Ng2 component I have developed called via-date-picker. My goal is to publish it on NPM so that it can be easily utilized in other projects. To achieve this, I converted it into a ...

Encountering the error message `TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"` with `ts-node` when the type is specified as module

After configuring absolute paths in my Express project and changing the type to module for using import, I encountered an error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" Below is the content of my tsconfig.json { &q ...

The Issue of Node.js Http POST Stalling Indefinitely During MySQL Queries

My goal is to verify if a username and email match in the database. If not, I want to register a new user using CoffeeScript. When attempting a POST request to the route, Morgan displays: POST /register - - ms - - However, Postman hangs indefinitely.. ...

Unveiling individual modules of an Angular library using public-api.ts in the latest version of Angular (Angular 13)

After completing an upgrade on my Angular library project from version 11 to 13, I encountered an issue when attempting to execute the ng build command. In version 11, the setup looked like this: I had multiple smaller modules, each containing various co ...

Vue 3 Composable console error: Unable to access properties of undefined (specifically 'isError') due to TypeError

I recently developed a Vue 3 / TypeScript Composable for uploading images to Firebase storage. The code snippet below illustrates the structure of the ImageUpload interface: interface ImageUpload { uploadTask?: UploadTask; downloadURL?: string; progr ...

Manipulating an Array of Objects based on conditions in Angular 8

I have received an array of objects from an API response and I need to create a function that manipulates the data by enabling or disabling a flag based on certain conditions. API Response const data = [ { "subfamily": "Hair ...

Ways to apply one watcher (subscription) across multiple components in Angular?

Within my Angular application, I am seeking a way for user preferences to be saved to the database using the backend API. This functionality should be implemented across all pages and components. Currently, I have the following code snippet: export class ...