devio95
devio95

Reputation: 9

Angular http get return undefined

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.

Upvotes: 0

Views: 4391

Answers (3)

Taranjit Kang
Taranjit Kang

Reputation: 2580

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

Upvotes: 0

mika
mika

Reputation: 343

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

Upvotes: 2

SeleM
SeleM

Reputation: 9638

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.

Upvotes: 0

Related Questions