【发布时间】:2018-05-22 13:50:57
【问题描述】:
使用服务和 api 连接到我能够在 catalog.component.ts 中显示我的 mongodb 集合中的整个数组: api.js
const express = require('express');
const router=express.Router();
const app=express();
const MongoClient=require('mongodb').MongoClient;
const ObjectID=require('mongodb').ObjectID;
var path=require('path');
var db;
const connection=(closure) => {
return MongoClient.connect('mongodb://localhost:27017', (err, client)=>{
if (err) return console.log(err);
db=client.db('angulardb');
closure(db);
});
};
const sendError =(err, res)=>{
response.status=501;
response.message=typeof err == 'object' ? err.message : err;
res.status(501).json(response);
};
let response={
status:200,
data:[],
message: null
};
router.post('/getProducts',(req, res) => {
connection((db) => {
db.collection('products')
.find()
.toArray()
.catch((err)=>{
sendError(err, res);
response.message ={ success:"Se obtuvieron los registros correctamente", error:""};
res.send({response});
})
.then((result)=>{
response.data= result;
res.send({response});
});
});
});
router.post('/getProduct',(req, res) => {
connection((db) => {
db.collection('products')
.find({id:new ObjectID(req.query.id)})
.toArray()
.catch((err)=>{
sendError(err, res);
response.message ={ success:"Se obtuvieron los registros correctamente", error:""};
res.send({response});
})
.then((result)=>{
response.data= result;
res.send({response});
});
});
});
module.exports=router;
我为目录添加了 getProducts 函数并为详细信息添加了 getProduct 函数的服务
mongo2.service.ts:
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
import {HttpClient, HttpHeaders} from '@angular/common/http';
@Injectable()
export class Mongo2Service {
constructor( private _http: HttpClient) { }
getProducts() {
const headers = new HttpHeaders({'Content-Type': 'application/json' });
return this._http.post('/api/getProducts', { headers })
.catch( (error: any) => Observable.throw(error || 'server error'));
}
getProduct(id: number) {
const headers = new HttpHeaders({'Content-Type': 'application/json' });
const params = {'id': id};
return this._http.post('/api/getProduct', { headers, params})
.catch( (error: any) => Observable.throw(error || 'server error'));
}
}
这里我从 mongodb 集合 catalog.component.ts 中获取数组:
import { Component, OnInit } from '@angular/core';
import {Mongo2Service} from '../mongo2.service';
@Component({
selector: 'app-catalog',
templateUrl: './catalog.component.html',
styleUrls: ['./catalog.component.css']
})
export class CatalogComponent implements OnInit {
products: any;
respuesta: any;
constructor( private mongo2Service: Mongo2Service) {}
ngOnInit() {
this.getProducts();
}
getProducts() {
this.mongo2Service.getProducts().subscribe(respuesta => {
this.respuesta = respuesta;
this.products = this.respuesta.response.data;
console.log(this.respuesta);
});
}
}
然后我会显示 mongodb 集合 collection 在此列表中: list
我将路由器链接添加到目录组件中的该列表,并将所选元素的 ID 添加到另一个名为“details”的组件中,该组件在 api 和服务中有一个“getProduct”方法,但视图不显示元素的名称或编号:
import { Component, OnInit } from '@angular/core';
import {Location} from '@angular/common';
import {ActivatedRoute} from '@angular/router';
import {Mongo2Service} from '../mongo2.service';
@Component({
selector: 'app-details',
templateUrl: './details.component.html',
styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit {
respuesta: any;
products:any;
constructor(private location: Location,
private route: ActivatedRoute,
,private mongo2Service: Mongo2Service) { }
ngOnInit() {
this.getProduct();
}
getProduct() {
const id=+ this.route.snapshot.paramMap.get('_id');
console.log('entro funcion componente');
this.mongo2Service.getProduct(id).subscribe(respuesta => {
this.respuesta = respuesta;
this.products = this.respuesta.response.data;
console.log(this.respuesta);
});
}
goBack(): void{
this.location.back();
}
}
【问题讨论】:
-
.find({ id: new ObjectID(req.query.id) })应该是.find({ _id: new ObjectID(req.query.id) })。那是_id而不是id作为ObjectId的主键检查您的输入并确保您发布的有效查询参数实际上提供了应该匹配的内容。如果仍然不确定,请显示您希望匹配的文档以及请求中实际发送的参数。 -
你能从
req.query.id得到id吗?试试console.log(req.query.id)> -
是的,我在运行details组件时可以看到路由上的id
标签: node.js angular mongodb express angular4-httpclient