IONIC post method is returning undefined value - node.js

ERROR MESSAGE
I tested the node js post on postman and it worked. However, when I made use of ionic serve, it will show the error as shown in the image above. This error occurred when I call the makePayment() function in the stripe.page.ts file. The data I retrieved through this.checkout.makePayment in the makePayment() function returns undefined. I am guessing that the issue is probably my node js isn't being triggered when I use ionic serve. Is there a way to solve this?
THIS IS MY checkout.service.ts FILE
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class CheckoutService {
constructor(private http: HttpClient) { }
makePayment(stripeToken: any): Observable<any>{
const url = "http://localhost:5040/checkout"
return this.http.post<any>(url,{token:stripeToken})
}
}
THIS IS MY index.js FILE
const express = require("express");
const bodyparser = require('body-parser')
const app = express();
app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())
const stripe = require("stripe")("###SECRETKEY###");
const cors = require('cors')
app.use(cors())
app.post('/checkout', function(req, res) {
try {
console.log(req.body);
token = req.body.token
const customer = stripe.customers
.create({
email: "cycoplayz#gmail.com",
source: token.id
})
.then((customer) => {
console.log(customer);
return stripe.charges.create({
amount: 1000,
description: "Test Purchase using express and Node",
currency: "USD",
customer: customer.id,
});
})
.then((charge) => {
console.log(charge);
res.json({
data:"success"
})
})
.catch((err) => {
res.json({
data: "failure",
});
});
return true;
} catch (error) {
return false;
}
})
app.listen(5040, () => {
console.log("App is listening on Port 5040")
})
THIS IS MY stripe.page.ts FILE
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { Loan } from '../shared/loan';
import { LoanService } from '../shared/loan.service';
import { ChargeInfo } from '../shared/models/chargeinfo';
import { CheckoutService } from '../shared/services/checkout.service';
#Component({
selector: 'app-stripe',
templateUrl: './stripe.page.html',
styleUrls: ['./stripe.page.scss'],
})
export class StripePage implements OnInit {
paymentHandler: any = null;
success: boolean = false
failure:boolean = false
loan: Loan;
loanid: string;
reason: string;
amount: number;
payment: number;
charged: ChargeInfo[] = [];
constructor(private checkout: CheckoutService, private route: ActivatedRoute, private
loanService: LoanService) {
this.loanid = this.route.snapshot.params.id
this.loanService.getChargesById(this.loanid)
.then(data =>{
this.reason = data.charges[0].reason;
this.amount = data.charges[0].amount;
})
}
ngOnInit() {
this.invokeStripe();
}
makePayment(amount: number) {
const paymentstripe = (stripeToken: any) => {
try{
this.checkout.makePayment(stripeToken).subscribe((data: any) => {
console.log(data);
if (data.data === "success") {
this.success = true
}
else {
this.failure = true
}
});
}
catch(err){
console.log(err);
console.log("hi");
}
};
const paymentHandler = (<any>window).StripeCheckout.configure({
key: '###PUBLISHABLE KEY###',
locale: 'auto',
token: function (stripeToken: any) {
console.log(stripeToken);
console.log(this.checkout.makePayment);
console.log(this.checkout.omg)
paymentstripe(stripeToken);
},
});
paymentHandler.open({
name: 'CHARGES',
description: this.reason,
amount: this.amount * 100,
});
}
invokeStripe() {
if (!window.document.getElementById('stripe-script')) {
const script = window.document.createElement('script');
script.id = 'stripe-script';
script.type = 'text/javascript';
script.src = 'https://checkout.stripe.com/checkout.js';
script.onload = () => {
this.paymentHandler = (<any>window).StripeCheckout.configure({
key: '###PUBLISHABLE KEY###',
locale: 'auto',
token: function (stripeToken: any) {
console.log(stripeToken);
},
});
};
window.document.body.appendChild(script);
}
}
}

Related

GraphQL Subscriptions is null using Express-GraphQL and graphql-subscriptions

I am using TypeScript and have Server and Client application. Below is the server code.
Server Code
import express, { Express } from "express";
import { graphqlHTTP } from "express-graphql";
import { buildSchema } from "type-graphql";
import { TaskResolver } from "./resolvers/task.resolver";
import { pgDatasource } from "./configs/db.config";
import { SeatBandingResolver } from "./resolvers/seatBanding.resolver";
import { GuestChatResolver } from "./resolvers/guestChat.resolver";
import { RateResolver } from "./resolvers/rate.resolver";
import { YearResolver } from "./resolvers/year.resolver";
import { ImplementationRateResolver } from "./resolvers/implementationRate.resolver";
import { UserResolver } from "./resolvers/user.resolver";
import { ReportResolver } from "./resolvers/report.resolver";
// Subscriptions
const ws = require("ws");
const { useServer } = require("graphql-ws/lib/use/ws");
const { execute, subscribe } = require("graphql");
const main = async () => {
const app: Express = express();
try {
//connect to db
await pgDatasource.initialize();
} catch (err) {
throw err;
}
//build gql schema
let schema = await buildSchema({
resolvers: [
SeatBandingResolver,
GuestChatResolver,
RateResolver,
YearResolver,
ImplementationRateResolver,
UserResolver,
],
validate: false,
// pubSub: new PubSub()
});
let schemaDoc = await buildSchema({
resolvers: [ReportResolver],
validate: false,
});
//ql schema for report
const docServer = graphqlHTTP((req, res) => {
return {
schema: schemaDoc,
graphiql: true,
context: {
req: req,
header: req.headers,
},
};
});
//setting a graphql server instance
const graphqServer = graphqlHTTP((req, res, graphQLParams) => {
return {
schema,
context: {
req: req,
header: req.headers,
},
graphiql: true,
};
});
app.use(cors());
//graphql endpoint : change it to backend
app.use("/graphql", graphqServer);
//for report : change name to google api
app.use("/doc", docServer);
//test route
app.get("/", (req, res) => {
res.json({
message: "Hello world",
});
});
let server = app.listen(3001, () => {
console.log("server started");
const wsServer = new ws.WebSocketServer({
host: "localhost",
// server,
path: "/graphql",
port: 3001,
});
useServer(
{
schema,
execute,
subscribe,
onConnect: (ctx) => {
console.log("Connect");
},
onSubscribe: (ctx, msg) => {
console.log("Subscribe");
},
onNext: (ctx, msg, args, result) => {
console.debug("Next");
},
onError: (ctx, msg, errors) => {
console.error("Error");
},
onComplete: (ctx, msg) => {
console.log("Complete");
},
},
wsServer
);
});
};
//starting a server
main()
.then(async (_) => {
// await addColumn()
})
.catch((err) => {
console.log(err);
});
Subscription Code at Client Side
import { Year } from "../entities/year.entity";
import { NewYear } from "../inputs/addYear.input";
import {
Arg,
Ctx,
Field,
Int,
Mutation,
ObjectType,
Query,
Resolver,
Root,
Subscription,
UseMiddleware,
} from "type-graphql";
import { Request } from "express";
import { Response } from "../helpers/response.helper";
import { Pagination } from "../inputs/pagination.input";
import { isAuth } from "../helpers/auth.helper";
import { PubSub, PubSubEngine } from "graphql-subscriptions";
const pubSub = new PubSub();
#ObjectType()
class MessagePayload {
#Field()
message: string;
}
#Resolver(() => Year)
export class YearResolver {
#Mutation(() => String)
async sendMessage(#Arg("message") message: string): Promise<string> {
console.log("in send subscription");
pubSub.publish("MESSAGE_NOTIFICATION", { message });
return message;
}
//calling the subscription
#Subscription(() => MessagePayload || null, {
topics: "MESSAGE_NOTIFICATION",
})
async receiveMessage(
#Root() root: MessagePayload
): Promise<MessagePayload | null> {
console.log("in publisher");
console.log(root, "in recieve message");
pubSub.asyncIterator("MESSAGE_NOTIFICATION");
return { message: "hello from the subscription" };
}
}
The issue I am facing here is Subscription is not working properly and the data is always null.
Can anyone help me to identify what I am missing here?
Thanks.
I'm not sure for 100% because your code descriptions are kinda confusing, but it looks like you should return pubSub.asyncIterator('MESSAGE_NOTIFICATION') in method receiveMessage. This method is called to start streaming messages to client at selected channel (MESSAGE_NOTIFICATION), not sending them. To send messages use pubsub. Of course you should change typing too.
You can find a similiar implementation here.

MEAN stack delete request has 404 not found error

My post request and list all request are working fine, but I have problem getting my delete request to work. I have tested in Postman, but still have error. I think my delete url is fine, I can console log and see the item id been selected and show at the end of the url when making the request, I don't know what 's wrong.
delete.component.ts
deleteItem(): void {
console.log(this.currentItem._id);
alert("You had redeemed free food "+this.currentItem.itemToDonate);
this.charityService.deleteItem(this.currentItem._id).subscribe(
() => console.log("All of this food item has been redeemed"),
(err) => console.log(err)
)
}
charity.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { identifierModuleUrl } from '#angular/compiler';
//import { DonateComponent } from '../donate/donate.component';
const AUTH_API = 'http://localhost:3000/api/auth/donate';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json'})
};
#Injectable({
providedIn: 'root'
})
//post new donates to the database, list all items on the beneficiary page
//update quantity after redeem, delete item if the quantity is 0
export class CharityService {
constructor(private http: HttpClient) { }
donate(itemToDonate: string, quantity: number): Observable<any> {
return this.http.post(AUTH_API, {
itemToDonate, quantity
}, httpOptions);
}
listItem(): Observable<any> {
return this.http.get(AUTH_API, {});
}
receive(id: string): Observable<any> {
return this.http.put(`${AUTH_API}/update/${id}`, httpOptions)
.pipe(
catchError((err, caught) => {
console.error(err);
throw err;
})
);
}
getItem(id: string): Observable<any> {
return this.http.get(`${AUTH_API}/${id}`);
}
deleteItem(id: string): Observable<any> {
return this.http.delete(`${AUTH_API}/${id}`)
}
}
route.js
const controller_donate = require("../controllers/donate.controller");
const controller_receive = require("../controllers/receive.controller");
const controller_list = require("../controllers/list.controller");
const controller_delete = require("../controllers/delete.controller");
module.exports = function(app) {
app.use(function(req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});
app.post("/api/auth/donate", controller_donate.donate);
app.get("/api/auth/donate", controller_list.donations);
app.put("/api/auth/donate/update/:id", controller_receive.receive);
app.delete("/api/auth/donate/:id", controller_delete.delete);
};
delete.controller.js
const db = require("../models");
const Donate = db.donate;
const { donate } = require("../models");
exports.delete = (req, res) => {
const id = req.params.id;
donate.findByIdAndRemove(id)
.then(data => {
if (!data) {
res.status(404).send({ message: "Cannot delete item" });
} else {
res.status(200).send("This item is been redeemed");
}
})
}

List is not updated for existing clients in socketIO

I am working on chat application, using socketIO
Whenever user signed in sucessfully, user is navigated to dashboard and list of current loggedin users will be displayed.
Whenever new user is signed in, existing user list is not getting updated.
Adding the necessary code here
events: backend
let verifyClaim = require("./tokenLib");
let socketio = require("socket.io");
let tokenLibs = require('./tokenLib');
let setService = (server) => {
let onlineUsers = [];
let io = socketio.listen(server);
let myio = io.of('')
myio.on('connection', (socket) => {
console.log(' emitting verify user');
socket.emit("verifyUser", "");
socket.on('set-user', (authToken) => {
console.log(authToken);
tokenLibs.verifyTokenWithoutSecret(authToken, (user, err,) => {
if (user) {
console.log(user);
let currentUser = user;
socket.userId = currentUser._id;
let fullName = `${currentUser.name}`
console.log(`${fullName} is online`);
socket.emit(currentUser._id, `${fullName} is online`)
let userObj = { userId: currentUser._id, name: fullName }
onlineUsers.push(userObj);
console.log(onlineUsers)
socket.emit('userlist', onlineUsers)
}
else {
socket.emit('auth-error', { status: 500, error: 'Please provide valid token ' })
}
})
})
socket.on('disconnect', () => {
console.log('user is disconnected');
let removeUserId = onlineUsers.map(function (user) { return user.userId }).indexOf(socket.userId)
onlineUsers.splice(removeUserId, 1)
console.log(onlineUsers)
})
})
}
module.exports = { setService: setService }
socket service:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class SocketService {
public prod = 'https://todolistbe.herokuapp.com/api/v1';
public dev = 'http://localhost:3001';
public baseUrl = this.dev;
private socket;
constructor(public http: HttpClient) {
this.socket=io('http://localhost:3001')
}
public verifyUser=()=>{
return Observable.create((observer)=>{
this.socket.on('verifyUser',(data)=>{
observer.next(data);
})
})
}
public setUser=(authToken)=>{
this.socket.emit("set-user",authToken)
}
public userList=()=>{
return Observable.create((observer)=>{
this.socket.on('userlist',(data)=>{
observer.next(data);
})
})
}
public welcomeUser=(userid)=>{
return Observable.create((observer)=>{
this.socket.on(userid,(data)=>{
observer.next(data);
})
})
}
public disconnectUser = () => {
return Observable.create((observer) => {
this.socket.on('disconnect', () => {
observer.next()
})
})
}
}
dashboard:
import { Component, OnInit } from '#angular/core';
import { ThemePalette } from '#angular/material/core';
import { SocketService } from '../../socket.service';
import { ToastrService } from 'ngx-toastr';
export interface Task {
name: string;
completed: boolean;
color: ThemePalette;
subtasks?: Task[];
}
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css'],
providers: [SocketService]
})
export class DashboardComponent implements OnInit {
public authToken: any = localStorage.getItem('authToken');
public userList: any = [];
public userNotification;
allComplete: boolean = false;
ngOnInit(): void {
this.verifyUserConfirmation();
this.getOnlineUsers();
}
public verifyUserConfirmation: any = () => {
this.SocketService.verifyUser().subscribe((data) => {
console.log(this.authToken)
this.SocketService.setUser(this.authToken);
this.getOnlineUsers();
})
}
selected = 'option2';
toggleNavbar() {
console.log('toggled' + this.isMenuOpened);
this.isMenuOpened = !this.isMenuOpened;
}
getOnlineUsers() {
// this.SocketService.welcomeUser(localStorage.getItem('id')).subscribe((data)=>{
// this.userNotification=data;
// console.log("hi:"+this.userNotification)
// })
this.SocketService.userList().subscribe((user) => {
this.userList = [];
for (let x in user) {
let tmp = { 'user': x, 'name': user[x] }
this.userList.push(tmp);
}
console.log(this.userList)
})
}
}
Whenever you want to emit an event with all other users, we should use myio.emit instead of socket.io.
Issue is resolved when i made necessary changed in my backend events library

i am trying to upload an image in MEAN stack application but when I click on submit button the page goes on for continous loading

here is my code
The screen just keeps loading whenever I click form submit button. No error is displayed however.Someone please help me with this. Thanks for the reply. I am using multer at backend and mime type validator for filtering mages of only jpeg,jpg and png images.
frontend:
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators } from "#angular/forms";
import{AdminteacherService} from '../Services/adminteacher.service';
import { MatSpinner } from '#angular/material';
import { HttpClient } from "#angular/common/http";
import { mimeType } from "./mime-type.validator";
import { ActivatedRoute, ParamMap } from "#angular/router";
import {TeacherModel} from '../../../backend/model/teacher';
#Component({
selector: 'app-adminteacher',
templateUrl: './adminteacher.component.html',
styleUrls: ['./adminteacher.component.css']
})
export class AdminteacherComponent implements OnInit {
enteredName = "";
enteredSSN = "";
enteredBranch = "";
enteredPassword = "";
post: TeacherModel;
isLoading = false;
form: FormGroup;
imagePreview: string;
private mode = "create";
private postId: string;
constructor(public postsService: AdminteacherService,
public route: ActivatedRoute,
private http:HttpClient) { }
ngOnInit() {
this.form = new FormGroup({
name: new FormControl(null, {
validators: [Validators.required, Validators.minLength(3)]
}),
ssn: new FormControl(null, { validators: [Validators.required] }),
branch: new FormControl(null, { validators: [Validators.required] }),
password: new FormControl(null, { validators: [Validators.required] }),
image: new FormControl(null, {
validators: [Validators.required],
asyncValidators: [mimeType]
})
});
}
onImagePicked(event:Event) {
const file = (event.target as HTMLInputElement).files[0];
this.form.patchValue({ image: file });
this.form.get("image").updateValueAndValidity();
const reader = new FileReader();
reader.onload = () => {
this.imagePreview = reader.result as string;
};
reader.readAsDataURL(file);
}
onSavePost() {
if (this.form.invalid) {
return;
}
this.isLoading = true;
if (this.mode === "create") {
this.postsService.addPost(
this.form.value.name,
this.form.value.image,
this.form.value.ssn,
this.form.value.branch,
this.form.value.password
);
}
postForm.value.ssn,postForm.value.password,postForm.value.branch,postForm.value.image);
this.form.reset();
}
}
SERVICE FILE:
import { HttpClient } from "#angular/common/http";
import { Subject } from "rxjs";
import { map } from "rxjs/operators";
import { Router } from "#angular/router";
import {TeacherModel} from '../../../backend/model/teacher';
#Injectable({
providedIn: 'root'
})
export class AdminteacherService {
constructor(private http:HttpClient) { }
postData:TeacherModel;
addPost(name: string,image:File,ssn: string,branch:string,password:string) {
const postData=new FormData();
postData.append("name",name);
postData.append("image",image,name);
postData.append("ssn",ssn);
postData.append("branch",branch);
postData.append("password",password);
console.log("I am here");
this.http
.post<{message: string; postId: string}>(
"http://localhost:3000/admin/addteacher",
postData
)
console.log("I am not here");
}
}
BACKEND:
const express=require("express");
const multer=require("multer");
const Post=require("../model/teacher");
const router=express.Router();
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/MyMINIPROJECT', { useNewUrlParser: true , useUnifiedTopology: true});
const MIME_TYPE_MAP={
'image/png' : 'png',
'image/jpeg' : 'jpg',
'image/jpg' : 'jpg'
};
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const isValid = MIME_TYPE_MAP[file.mimetype];
let error = new Error("Invalid mime type");
if (isValid) {
error = null;
}
cb(error, "./images");
},
filename: (req, file, cb) => {
const name = file.originalname
.toLowerCase()
.split(" ")
.join("-");
const ext = MIME_TYPE_MAP[file.mimetype];
cb(null, name + "-" + Date.now() + "." + ext);
}
});
router.post('/admin/addteacher', multer({ storage: storage }).single("image"),
(req, res, next)=>{
const url = req.protocol + "://" + req.get("host");
console.log("reached backend");
const post=new Post({
name:req.body.name,
img_link: url + "/images/" + req.file.filename,
ssn:req.body.ssn,
branch:req.body.branch,
password:req.body.password
});
post.save().then(createdPost => {
res.status(201).json({
message: "Post added successfully",
post: {
...createdPost,
id: createdPost._id
}
});
});
});
module.exports = router;

MEAN stack: can't display data from a single Mongodb element by it's id

using a service and api to connect to I was able to display the whole array from my mongodb collection in catalog.component.ts :
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;
service where I added the getProducts function for catalog and getProduct function for details
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'));
}
}
Here I get the array from mongodb collection 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);
});
}
}
And I get displayed the mongodb collecction
collection
in this list:
list
I add a router link to that list in catalog component with the selected element's id to another component called 'details' which has a 'getProduct' method in api and the service, but the view doesn't display the element's name or 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();
}
}
I solved it , I edited the getProduct method in api.js by changing req.query._id for req.body.id inside find.() as you can see:
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});
});
});
});
I also deleted the '+' at the const id and added another variable (product:any) to the method in details with the position [0] in data.
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);
});
}
MongoDB creates _id and not id, your match condition is wrong for getting the results.
I have updated the query and added the console log, check the console if you're getting expected result now.
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)=>{
console.log("Expected Results: ", result);
response.data= result;
res.send({response});
});
});
});
This should get you details for the single product. Check how you are using the returned data here.

Resources