我有这个问题。当我尝试订阅从服务返回的数据时,我在尝试记录时未定义。
这是我的路线,我已经使用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}}”错误。