-3

I use a service function in my Angular 4 app to retrieve data from the MongoDB/Express.js backend:

getArticles() {
  return this.http.get('api/articles').map(res => res.json());
}

How do I get the length of the received array?

Update:

I should have clarified, I needed to find a length of an Observable array.

mikebrsv
  • 1,890
  • 2
  • 24
  • 31
  • 1
    Possible duplicate of [Length of a JavaScript object](https://stackoverflow.com/questions/5223/length-of-a-javascript-object). If you're just looking for the length of an object, that question has been asked and answered dozens, if not hundreds, of times on here. In short, `var size = Object.keys(myObj).length;` – Jason Oct 07 '17 at 22:32
  • Try this.https://stackoverflow.com/questions/41121284/angular-2-mean-stack-receiving-json-instead-of-html – harold_mean2 Oct 07 '17 at 23:12

2 Answers2

2

var size = Object.keys(myObj).length;. Object.keys() 'returns an array of a given object's own enumerable properties', from MDN. So if you do Object.keys(myObj) you will get an array of enumerable properties. Doing .length on that array will provide you with the number of enumerable properties.

Jason
  • 514
  • 5
  • 21
1

Found the solution here: https://stackoverflow.com/a/40237063/5861479 In my case it would be something like this:

getArticlesLength() {
  return this.http.get('api/articles')
    .map(res => res.json()).subscribe(result => {console.log(result.length)});
}
mikebrsv
  • 1,890
  • 2
  • 24
  • 31