0

I have a express router get

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Stats = require('../models/Stats.js');

/* GET ALL STATS */
router.get('/', function(req, res, next) {
  Stats.find(function (err, products) {
    if (err) return next(err);
    res.json(products);
  });
});

Also api

 getAll(){
    this.http.get('/main').subscribe(data => {
      console.log(data);
      return data;
    });
  }

And i am using it in component

show(){
      console.log(this.api.getAll());
   }

Problem is that when i log data in api getAll() data is returned well, but if i log data in component i have undefined.

3 Answers 3

2

In getAll() you should return the observable:

getAll(){
   return this.http.get('/main');
}

And then in where you call the function you subscribe to the observable:

show(){
  this.api.getAll().subscribe((data) => {
       // Here you can do what you want with the data.
       console.log(data)
   })
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your service or API within Angular should just be calling the backend service and not subscribing via in the service itself but rather in the component.

Service:

getAll(){
  return this.http.get('/main');
}

Component:

this.service.getAll().subscribe((data)=> {
   // Your Data
},error => {
   console.log('error: ', error)
});

Comments

0

Your service should return, change your service to

getAll(){
    return this.http.get('/main').subscribe(data => {
      console.log(data);
      return data;
    });
  }

And it is better to subscribe in the component part not while declaring your services.

2 Comments

Now the show() function is only going to log the observable returned by getAll().
@mika what ?? you're wrong ! it is already subscribed there why would it return observable ??, reread what i'd written.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.