Search code examples
node.jsangularmongodbexpressangular-httpclient

Angular: pass JS type 'Number' to an HTTP response


I'm working on a MEAN app (Mongo, Express, Angular, Node). I want to make a GET route in Express that uses Mongo's countDocuments() method to return the total number of entries in a collection.

GET route:

app.get('/total', (req, res) => {
  collection.countDocuments({}, function(err, num) {
    assert.equal(null, err);
    var total = {'total' : num}
    res.send(total);
  });
});

I made the total object because it's my understanding that Angular's HttpClient module only works with data if it's formatted in JSON. I tried to pass num directly as res.send(num) but it wouldn't work. I think it's because typeof(num) returns Number and not Object.

The route above works but making the total object seems like a hack to me. Is there a more efficient way to pass something of type Number so that it's ready to be consumed by Angular?

Here is the relevant Angular component code:

export class AppComponent implements OnInit {
  total: object;

  constructor(private http: HttpClient){

  }

  ngOnInit(): void {
    this.http.get('http://localhost:1337/total').subscribe(
      data => {
        this.total = data;
      }
    );
  }
}

Solution

  • If you send a number in res.send in express, It takes it as status code so sending a number of type Number is not allowed, There are 2 solutions.

    Solution: 1

    var result = 5;
    res.send(result.toString());
    

    Sent it as string, And in Client side use parseInt.

    Solution: 2

    var result = 5;
    res.send({result}); //Iquivalent to { result: 5 }
    

    Send an object as you mentioned.