MEAN堆栈:无法通过ID显示来自单个Mongodb元素的数据

阿拉米斯·德尔加多(Aramis Delgado)

使用服务和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 collecction集合list

我将路由器链接添加到目录组件中该列表的列表,并将所选元素的ID添加到另一个名为“详细信息”的组件,该组件在api和服务中具有“ getProduct”方法,但是视图不显示元素的名称或ID:

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();
  }
}
阿拉米斯·德尔加多(Aramis Delgado)

我解决了它,我改变编辑在api.js的getProduct方法req.query._idreq.body.id找到里面的(),你可以看到:

router.post('/getProduct',(req, res) => {
  var find={ id: new ObjectID(req.body.id) };
  console.log(find);
  connection((db) => {
    db.collection('products')
      .find({_id:new ObjectID(req.body.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});
      });
  });
});

我还删除了const id处的“ +”号,并向该方法添加了另一个变量(product:any),该变量的详细信息在数据中的位置为[0]。

 getProduct() {

    const id = this.route.snapshot.paramMap.get('_id');

    console.log(id);
    this.mongo2Service.getProduct(id).subscribe(respuesta => {
      this.respuesta = respuesta;
      this.product = this.respuesta.response.data[0];
      console.log(this.respuesta);
    });
  }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章