Having trouble with my Angular CLI post request to localhost:3000, could be due to an issue with my Proxy setup

I've set up a basic local API that focuses solely on handling post requests. I'm currently attempting to integrate this post request into my Angular application, but the results are rather puzzling. It seems like there's a misstep on my end, causing the app to not return the expected outcome. Below is the code snippet:

1/ app.component.html

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Welcome to the parentheses balance checker';
  result;
  test = "hello";

  constructor(private http: HttpClient) {}

    onSubmit(textEnter: string) {
      let json = { "string": textEnter };
      console.log(json);
      this.result = this.http.post('http://localhost:3000/parentheses/', json);
    }
}

2/ app.components.ts

<div>
  <form>
     <input #textEnter placeholder="text">
     <button type="submit" (click)="onSubmit(textEnter.value)">click here</button>
  </form>

  <pre><code>proxy.config.json file:

{
  "/parentheses":{
    "target": "http://localhost:3000",
    "secure": false,
    "logLevel1": "debug"
  }
}

4/ The API in question is essentially a parentheses checker:

const parenthesesChecker = require('./checker.js');

const express = require('express'), bodyParser = require('body-parser');
const router = express.Router();

router.use(bodyParser.json());

router.post('/', (req, res, next) => {
  const stringCheck = ({
    string: req.body
  });
  if (parenthesesChecker(stringCheck.string.string).result === true) {
    res.status(200).json({
      "isValid": true
    });
  } else {
    res.status(400).json({
      "isValid": false,
      "errorDetails": {
          "preceedingParentheses": `${parenthesesChecker(stringCheck.string.string).preceeding}`,
          "erroneosParentheses": `${parenthesesChecker(stringCheck.string.string).erroneos}`
      }
    });
  };
});

module.exports = router;

5/ The JavaScript function being referenced:

module.exports = function (string) {
  const openArray = ["(", "[", "{", "<"];
  const closeArray = [")", "]", "}", ">"];
  let i = 0, parOpen = 0, openingPar= "", closingPar = [], erroneos = "";
  for(i; i < string.length; i++) {
    if (openArray.includes(string[i])) {
      openingPar += string[i];
      parOpen++;
      closingPar.push(closeArray[openArray.indexOf(string[i])]);
    }
    if (closeArray.includes(string[i])) {
      let erroneos = string[i];
      parOpen--;
      if (string[i] === closingPar[closingPar.length - 1]) {
        closingPar.pop();
      } else {
        return { result: false, preceeding: openingPar, erroneos: erroneos };
      };
    };
    if (parOpen < 0) return { result: false, preceeding: openingPar, erroneos: erroneos };
  }
  return { result: (parOpen === 0 ? true : false), preceeding: openingPar, erroneos: erroneos };
};

My issue: The return I'm getting is quite perplexing, as it only flashes for a split second:

  {
*_isScalar*: false,
  *source*: {
    *_isScalar*: false,
    *source*: {
etc..

Deciphering this output has proven to be a challenge for me.

Answer №1

When attempting to retrieve data from a network source, utilizing the http method will result in an observable being returned. To access the data once it is available, you must subscribe to the observable:

Your initial code may look like this:

  this.result = this.http.post('http://localhost:3000/parentheses/', json);

However, it should be structured like this:

  this.http.post('http://localhost:3000/parentheses/', json).subscribe((data) => {
    this.result = data;
    console.log(this.result);
 });

For further information, please refer to: observable

In your HTML, you also have the option to utilize the async pipe instead of subscribing directly. Here's an example:

<div>
  <form>
     <input #textEnter placeholder="text">
     <button type="submit" (click)="onSubmit(textEnter.value)">click here</button>
  </form>

  <pre>
    {{ result | async | json }}
  </pre>

</div>

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

Enhancing Data Retrieval in Next.js: Implementing Typed Requests and Responses with the Fetch API

Context I've been developing a web application using Next.js and a custom Django Python backend, but I am struggling to find an efficient approach for making API requests from my frontend to the backend. My main goal is to centralize the logic for fet ...

Issue occurred when trying to load controllers during the migration process from AngularJS1 to Angular6

Currently, I am in the process of upgrading AngularJS1 components to Angular6. My strategy involves creating wrappers for all existing AngularJS1 components by extending "UpgradeComponent" and storing them under the folder "directive-wrappers". However, wh ...

Angular 2 ngx-modal: A User-Friendly Modal Component

I have encountered an issue while trying to implement a modal form in my Angular application. Even though my code seems correct and I have installed ngx-modal as well as imported the ModalModule in my app.module.ts, the modal form is not responding. Any ...

Issue with DevExtreme nested table not expanding when sorting the parent table

Utilizing the DevExtreme Nested Data Grid (dx-data-grid) within an Angular app to exhibit hierarchical data is proving challenging for me. The data structure comprises a parent table, where each row can have child rows, which in turn can have grandchild ro ...

Steps to configure Visual Studio Code to automatically open the original TypeScript file located in the "src" folder when a breakpoint is hit in a Node.js application

I am currently working on a CLI node application and using VSCode to debug it. Everything seems to be working fine, except for one annoyance: when I hit a breakpoint, VSCode opens the source map file instead of the actual TypeScript file located in my "src ...

A warning has been issued: CommonsChunkPlugin will now only accept one argument

I am currently working on building my Angular application using webpack. To help me with this process, I found a useful link here. In order to configure webpack, I created a webpack.config.js file at the package.json level and added the line "bundle": "web ...

Exploring Angular: Embracing the Power of Query String Parameters

I've been struggling with subscribing to query string parameters in Angular 2+. Despite looking at various examples, I can't seem to make it work. For instance, on this Stack Overflow thread, the question is about obtaining query parameters from ...

Trigger a (click) or (keyup) event in Angular 4+ only when the value meets the specified pattern

Here is the HTML code snippet. The keyup event will only be triggered if the value in the input field matches the specified pattern. <input (keyup)="checkPatternMatch(ProjectName)" type="text" #ProjectName="ngModel" name="pro-name" class="form-control" ...

Can you define the type of binding value in AngularJS 1.5(6) using TypeScript?

I am looking to define the type of binding items so that I am able to utilize components similar to functions. For instance, consider a component: angular.module('app').component('navBar', new NavBar()); class NavBar{ public bin ...

Definition of union types in JavaScript using Typescript

Looking for assistance in creating a d.ts file for the union-type library found at https://github.com/paldepind/union-type Consider the following union type: let Maybe = Type({ Nothing: [] , Just: [Number] }) I am interested in setting up compi ...

What is the best way to convert dates in Angular's DatePipe using moment.js?

My current package versions are as follows: "@angular/cdk": "^11.2.13", "@ngx-translate/core": "^13.0.0", "@angular/material-moment-adapter": "^12.2.9", "moment": "^2.29.1", &q ...

Firebase cloud function encountered an issue: Error: EISDIR - attempting to perform an unauthorized operation on a directory

I am currently working on a task that involves downloading an image from a URL and then uploading it to my Firebase cloud storage. Below is the code I have implemented for this process. import * as functions from 'firebase-functions'; import * a ...

Facing issue during deployment with error message "module typescript not found"

I am experiencing difficulties with deploying my application. It is a server built using fastify and typescript. Below is my package.json: { "name": "expense-manager-back", "version": "1.0.0", "descr ...

Using static methods within a static class to achieve method overloading in Typescript

I have a TypeScript static class that converts key-value pairs to strings. The values can be boolean, number, or string, but I want them all to end up as strings with specific implementations. [{ key: "key1", value: false }, { key: "key2&qu ...

Can an object's keys be strongly typed according to array values?

To utilize normalized data effectively, I have created an object with keys that can only be a list of numbers within a specified array. Is there a way to enforce this restriction in typing so that if I attempt to access the object using a non-array key, an ...

Tips for effectively narrowing the `undefined` type

Why am I getting this error message? const func = (a: unknown) => { if (a && typeof a === 'object' && 'b' in a) { a.b; } }; The error message I'm receiving is: Property 'b' does not exist on ty ...

Implementing ValidateAntiForgeryToken with Angular 7 and ASP.NET Web API: Step-by-Step Guide

Currently, my application's server side is constructed using Asp.Net web api while the client side uses Angular 7. I have come across numerous examples demonstrating how to incorporate ValidateAntiForgeryToken in various scenarios such as web forms, ...

How to access NavController in an Ionic2 service provider

In my Ionic2 app, I have created an AuthHttpProvider which acts as a wrapper for Http requests and automatically adds an authentication token (jwt) to each request. I use this instead of the default Http provider in all of my interactions with the server. ...

Issue encountered in app.module.ts while attempting to incorporate AngularMultiSelectModule

Currently, I am utilizing angular version 6 and attempting to incorporate the angular2-multiselect-dropdown in my application. Upon launching the app and following the steps outlined in this guide: and also here: https://www.npmjs.com/package/angular2-mul ...

Managing a single Angular project with multiple apps that share common features: A guide

Imagine having multiple Angular 'apps' with similar features and functions, where one product needs to be customized for different clients with slightly varying needs. The challenge lies in developing within a single code base. Using feature mod ...