订阅服务时,值未定义

时间:2018-05-15 17:53:11

标签: javascript node.js angular typescript

我有这个问题。当我尝试订阅从服务返回的数据时,我在尝试记录时未定义。

这是我的路线,我已经使用REST客户端对其进行了测试,并且工作正常:

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

这是我从mongoDB获取数据的方法:

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

这是我的服务:

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.

这是我的组件。:

this.liveAuction._id

此外,如果我尝试使用其中的get项,例如Cannot find property _id of undefined,则会出现“{{1}}”错误。

你可以帮我理解我做错了什么吗?我已经为我的其他组件做了类似的程序,我将其用作具有不同服务的Mat-Dialog组件,但功能完全相同。我已经将它们比作三次了,一切看起来都一样,但在这里它不起作用。请告诉我我做错了什么。谢谢!

0 个答案:

没有答案