0

I have this problem. When I am trying to subscribe to a data returned from service I get undefined when trying to log it.

This is my route, I have tested it with REST client and it works fine:

router.post('/liveAuction', (req, res, next) => {
const id = req.body.id;

Auction.getAuctionById(id, (err, liveAuction) => {
    if (err){
        res.json({
            success: false,
            message: "Something went wrong!"
        });
        console.log(err);
    }
    else {
        res.json({
            success: true,
            message: "Auction retrieved!",
            liveAuction
        });
    }
});
});

This is my method of getting data from mongoDB:

module.exports.getAuctionById = function(id, callback){
   const query = {_id: id};
   Auction.find(query, callback);
   console.log(query);
}

This is my service:

getAuctionById(id):any{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/auctions/liveAuction', {id: id}, {headers: headers})
  .map(res => res.json());
}

And this is my component.ts:

import { Component, OnInit, ElementRef, Inject } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import {Router, RoutesRecognized} from '@angular/router';
import { AuctionService } from '../../services/auction.service';
import { DataTransferService } from '../../services/data-transfer.service';


@Component({
  selector: 'app-auction-details',
  templateUrl: './auction-details.component.html',
  styleUrls: ['./auction-details.component.css']
})
export class AuctionDetailsComponent implements OnInit {

  liveAuction: any;
  auction: any;
  id: any;


  constructor(
    private auctionService: AuctionService,
    private dataService: DataTransferService
  ) {
    this.dataService.currentProduct.subscribe(auction => this.auction = auction);
    this.id = this.auction._id;
    console.log(this.auction._id);// I get the right id here.
  }


  ngOnInit() {
    this.auctionService.getAuctionById(this.id).subscribe(auction => this.liveAuction = auction.liveAuction);

    console.log(this.liveAuction);// Here I get undefined.

Also if I try to use get items of it, like this.liveAuction._id, I get "Cannot find property _id of undefined" error.

Could you help me understand what I am doing wrong? I have done similar procedure for my other component which I use as Mat-Dialog component with different service, but functionality is completely the same. I have compared them like three times already and everything looks same but here it doesn't work. Please suggest what I am doing wrong. Thanks!

Martin
  • 177
  • 1
  • 11
  • An observable has an asynchronous flow. The block code inside the .subscribe() method runs after that console.log(this.liveAuction). You have to wait the observable emits a value to access it. You can't think in a synchronous way. – Christian Benseler May 15 '18 at 18:03
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ConnorsFan May 15 '18 at 18:17

0 Answers0