0

I am new to Angular, APIs, node.js and coding in general. I have my API that only includes a POST request that works fine in Postman. I am trying to integrate it to an Angular app just for testing, but I am stuck, and a little help would be most appreciated. What I want to do is very simple. A user can enter a string that contains different types of parentheses (or none at all), and the API returns whether the entry is valid or not depending on whether the parentheses are balanced or not.

But I only get null as a response, and I am not sure how to approach this. Here are my codes.

1/ First my API:

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;

2/ Here is the Javascript function the API is calling:

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 };
};

Now let's move to the Angular part:

3/ The form, and the result that I wish to display in my app.components.html file

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

  <pre>
    {{ (result | async) | json }}
  </pre>
</div>

4/ My app.components.ts file:

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 = 'Enter your String bellow:';
  result;
  test = "hello";

  constructor(private http: HttpClient) {};

  onSubmit(textEnter: string) {
    const json = {
    "string": textEnter
  };

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

I guess that is all you need, but let me know if you want to see more stuff. It seems to be working to some extent because when I run my API with npm start and I pass in a string instead of a json, I get an error message in the terminal.

Also, as you can see I console.log(json); in the app.component.ts file. It does appear in the console, but super briefly, why is that?

Looking forward to anything that can help me move forward, I have been at it almost all day! Thanks!

Olivier Girardot
  • 389
  • 4
  • 16
  • Move the `console.log(json);` inside the `then` callback and check the response in the console. You can then display the value in the template using `{{ result | json }}` – Nicholas K Jun 30 '20 at 17:06
  • Also, you can use observables rather than a promise for an api call. – Nicholas K Jun 30 '20 at 17:09
  • Thank you! But unfortunately this did not work. Moving the console.log doesn't console.log anything anymore (not even for a millisecond anymore). And ```{{ result | json }}``` doesn't display anything as opposed to ```{ (result | async) | json }}``` which would display ```null``` May I ask, how would I use observables in this situation? – Olivier Girardot Jun 30 '20 at 17:19
  • 1. Check if your api call is failing from the network tab 2. Using observables: `this.http.post('http://localhost:3000/parentheses', json).subscribe( (res) => { this.result = data.json; console.log(this.result); }, err => { console.log(err); } );` – Nicholas K Jun 30 '20 at 17:23
  • Also, It looks like you need to pass headers to your API. You may do so by using [this answer](https://stackoverflow.com/a/47757775/6139527) as a reference. – Nicholas K Jun 30 '20 at 17:32
  • I really appreciate you trying to help me, thanks! Unfortunately nothing seems to be working, or even changing anything. Could the problem come from somewhere else in my app? Also would you happen to know why the console.log only appears for a few milliseconds in the console? – Olivier Girardot Jun 30 '20 at 19:40
  • maybe it comes from the fact that I closed this without the content that is bellow: ```constructor(private http: HttpClient) {};``` ? – Olivier Girardot Jun 30 '20 at 20:18
  • 1. Your code looks fine. Did you observe any errors in the console after making the changes I suggested? Also, to really pin-point the issue can you replicate this problem in stackblitz? – Nicholas K Jul 01 '20 at 04:46

0 Answers0