Golden Layout Dynamic Tabs - Data change on click - node.js

I have created React.js Project with Golden Layout. As you see the image below it's possible to open up three other sub windows by clicking first "View Button", but when I click the second view button the data does not change, I am not able to find where I am going wrong.
First View
Second View
When trying to apply the content to the other three tabs, I get the above error.
App.js File
import React from 'react';
import './App.css';
import Applications from './components/applications';
const $ = window.$;
const App=() =>{
var config = {
content: [{
type: 'row',
content: [{
title: 'Parties',
type:'react-component',
component: 'Applications',
isClosable:false
}
]
}]
};
var myLayout = new window.GoldenLayout( config, $('#layoutContainer') );
myLayout.registerComponent( 'Applications', Applications);
myLayout.init();
return (
<div></div>
);
}
export default App;
Application.js
import React, { Component } from 'react';
import data from '../common'
import titlesparcels from './titlesparcels';
import Services from './Services';
import Document from './document';
import GoldenLayout from 'golden-layout';
let DataValue = [];
class Applications extends Component {
constructor(props){
super(props);
this.state = {
userData: ''
}
}
renderHeader(){
return(
<div >
<table style={{width: 100 + 'em'}} className="table table-striped">
<thead>
<tr>
<th>Application Id</th>
<th>agent</th>
<th>status</th>
<th>partyType</th>
<th>lodgedDate</th>
<th>View</th>
</tr>
</thead>
</table>
</div>
)
}
renderData(){
console.log("in")
DataValue = data.applications;
return DataValue.map((val,key)=>{
return(
<div key={val.id}>
<table className="table table-striped">
<tbody>
<tr>
<td>{val.general.applicationId}</td>
<td>{val.general.agent}</td>
<td>{val.general.status}</td>
<td>{val.general.partyType}</td>
<td>{val.general.lodgedDate}</td>
<td><button onClick={()=> this.showTble(val.id)} >View</button></td>
</tr>
</tbody>
</table>
</div>
)
});
}
showTble=(id)=> {
console.log("User :",this.props,"appId",id)
global.sendId = id;
this.setState({
userData: id
})
this.props.glEventHub._layoutManager.eventHub.emit('params','stateChanged' );
if(this.props.glEventHub._layoutManager){
let myLayout = this.props.glEventHub._layoutManager;
if(myLayout.root.contentItems[0].contentItems.length-1 >1){
this.forceUpdate()
}else{
var titleparcels = {
title: 'Titles & Parcels',
type: 'react-component',
component: 'titlesparcels',
isClosable:false,
props: {"id":id}
};
var services = {
title: 'Services',
type: 'react-component',
component: 'Services',
isClosable:false,
props: {"id":id}
};
try{
let window = 0;
myLayout.registerComponent( 'titlesparcels', titlesparcels);
myLayout.registerComponent( 'Services', Services);
myLayout.registerComponent( 'Document', Document);
myLayout.root.contentItems[0].addChild( titleparcels );
myLayout.root.contentItems[0].addChild( services );
data.applications.map((val,key)=>{
if(val.id === id){
val.documents.forEach(element => {
var document = {
title: 'Documents',
type: 'react-component',
component: 'Document',
isClosable:false,
props: {"doc":element.source}
};
if(window == 0){
console.log("window")
myLayout.root.contentItems[0].addChild( document );
window++;
}else{
window++;
console.log('data')
myLayout.root.contentItems[0].contentItems[3].addChild( document );
}
});
}
});
}catch(e){
alert (e)
console.log(e)
}
}else{
}
}
render() {
if(this.props.data){
let value = this.pro
console.log("value from userData",value)
}
return (
<div>
{this.renderHeader()}
{this.renderData()}
<titlesparcels userId={this.state.userData} />
</div>
);
}
}
export default Applications;

Related

How to export nested json into Excell

How can I export into Excel the following object:
{
"EAN": "541448820055773131",
"city": "Geel",
"ECAID": [
"4044123",
"9006670"
],
"document_reference": [
"EM-10006129",
"EM-10006134"
]
}
I have this React code that exports only top-level items:
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import axios from 'axios'
import { ExportToExcel } from "../Excelexport";
const Record = (props) => (
<tr>
<td>{props.record.EAN}</td>
</tr>
);
export default function RecordList() {
const [records, setRecords] = useState([]);
const fileName = "myFile"
useEffect(() => {
async function getRecords() {
const response = await fetch(`http://localhost:5000/records/`);
const records = await response.json();
setRecords(records);
}
getRecords();
return;
}, [records.length]);
function recordList() {
return records.map((record) => {
return (
<Record
record={record}
deleteRecord={() => deleteRecord(record._id)}
key={record._id}
/>
);
});
}
return (
<div>
<h3>Record List</h3>
<ExportToExcel apiData={records} fileName={fileName} />
<table className="table table-striped" style={{ marginTop: 20 }}>
<thead>
<tr>
<th>EAN</th>
</tr>
</thead>
<tbody>{recordList()}</tbody>
</table>
</div>
);
}
ExportJS component looks like this:
import React from 'react'
import * as FileSaver from "file-saver";
import * as XLSX from "xlsx";
export const ExportToExcel = ({ apiData, fileName }) => {
const fileType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
const fileExtension = ".xlsx";
const exportToCSV = (apiData, fileName) => {
const ws = XLSX.utils.json_to_sheet(apiData);
const wb = { Sheets: { data: ws }, SheetNames: ["data"] };
const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
const data = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(data, fileName + fileExtension);
};
return (
<button onClick={(e) => exportToCSV(apiData, fileName)}>Export to Excel</button>
);
};
I want to see nested components like:
"ECAID": [
"4044123",
"9006670"
],
"document_reference": [
"EM-10006129",
"EM-10006134"
]
Also show up in Excel.
Is this even good approach? Possibly the array needs to be flattened somehow but I don't see how this would be done here.

mongoose cant display private message data

I am pretty new with mongoose & node.js and I am having an issue with displaying my users messages privately.
The message recipient, sender and message content is stored in the database.
but when I want to see the message's between two users, the messages between two users are displayed on every user messages tab!.
(developing in MEAN stack environment)
The Problem: https://i.imgur.com/qfDlMml.mp4
Messages Schema:
var messageSchema = new mongoose.Schema({
id: {
type: Number,
},
senderId: {
type: Number
},
senderUsername: {
type: String
},
recipientId: {
type: Number
},
recipientUsername: {
type: String
},
content: {
type: String,
required:true
},
dateRead: {
type: Date
},
messageSent: {
type: Date
},
senderDeleted: {
type: Boolean
},
recipientDeleted: {
type: Boolean
}
},
{
collection: 'messages',
timestamps: true
},
);
module.exports = mongoose.model('Messages', messageSchema)
User route:
//Get Message Of User
usersRoute.route("/messages/thread/:username/:senderUsername").get((req, res) => {
Messages.find(({ data: { "$in" : [req.params.senderUsername,req.params.username]} }, (error, data) => {
if (error) {
console.log(error)
throw error;
}
res.json(data);
}))
})
messages.service:
getMessageThread(username: string,sender:string) {
return this.http.get<Message[]>(`${AUTH_API}messages/thread/${username}/${sender}`);
}
member-messages.ts:
import { Component, OnInit, Input } from '#angular/core';
import { NgForm } from '#angular/forms';
import { Message } from 'src/app/models/message';
import { User } from 'src/app/models/user';
import { AccountService } from 'src/app/services/account.service';
import { MessageService } from 'src/app/services/message.service';
import { Observable, take } from 'rxjs'
import { ActivatedRoute } from '#angular/router';
import { MembersService } from 'src/app/services/members.service';
#Component({
selector: 'app-member-messages',
templateUrl: './member-messages.component.html',
styleUrls: ['./member-messages.component.css']
})
export class MemberMessagesComponent implements OnInit {
#Input() username: string;
#Input() messages: Message[];
user: User;
member: any;
currentUser$: Observable<User | null>;
messageContent: string;
constructor(
private messageService: MessageService,
private accountService: AccountService,
private route: ActivatedRoute,
private memberService: MembersService
) {
this.accountService.currentUser$.pipe(take(1)).subscribe(x => {
this.currentUser$ = this.accountService.currentUser$;
this.user = x as User;
});
}
ngOnInit() {
const username = this.route.snapshot.paramMap.get('username') as string;
this.memberService.getMember(username).subscribe(member => {
this.member = member;
});
}
sendMessage(form: NgForm) {
this.messageService.sendMessage(this.username, this.messageContent, this.user)
.subscribe((message) => {
this.messages.push(message as Message);
form.reset();
})
}
}
member-messages.html:
<div class="card">
<div class="card-body">
<ng-container *ngIf="messages && messages.length; else noMessages">
<ul class="chat">
<li *ngFor="let message of messages.slice().reverse()">
<span class="chat-img float-right">
<img class="rounded-circle" *ngIf="message.senderUsername && member.username == message.recipientUsername" src="{{user.profile_img || './assets/user.jpg'}}"> <span *ngIf="message.senderUsername && member.username == message.recipientUsername" style="color:red"> {{message.senderUsername}}</span> <img class="rounded-circle" *ngIf="message.recipientUsername && member.username != message.recipientUsername " src="{{member.profile_img || './assets/user.jpg'}}"><span *ngIf="message.recipientUsername && member.username != message.recipientUsername" style="color:green"> {{member.username}}</span>
</span>
<div class="chat-body" >
<p >{{message.content}}</p>
</div>
</li>
</ul>
</ng-container>
<ng-template #noMessages>No messages Yet... say hi bu using the message box bellow</ng-template>
</div>
<div class="card-footer">
<form #messageForm="ngForm" (ngSubmit)="sendMessage(messageForm)" autocomplete="off">
<div class="input-group">
<input
name="messageContent"
required
[(ngModel)]="messageContent"
type="text"
class="form-control input-sm"
placeholder="Send a private message">
<div class="input-group-append">
<button [disabled]="!messageForm.valid" class="btn btn-primary" style="border-radius:0px 5px 5px 0px"type="submit"> Send </button>
</div>
</div>
</form>
</div>
</div>
I think the problem is that you are trying to query for the data field but this field does not exist in your data model.
Solution is to ask data model for messages which contain senderUsername and recipientUsername in the database.
usersRoute
.route("/messages/thread/:username/:senderUsername")
.get(async (req, res) => {
const query = {
senderUsername: req.params.senderUsername,
recipientUsername: req.params.username,
};
const messages = await Messages.find(query).exec();
res.json(messages);
});
Ok, so I managed to find a work around, created another query only this time the senderUser value will be the recipient username and recipientUsername value as the senderUsername :
const query2 = {
senderUsername: req.params.username,
recipientUsername: req.params.senderUsername,
};
Find with both quires while using $or:[query,query2].
the following example worked:
usersRoute
.route("/messages/thread/:username/:senderUsername")
.get(async (req, res) => {
const query = {
senderUsername: req.params.senderUsername,
recipientUsername: req.params.username,
};
const query2 = {
senderUsername: req.params.username,
recipientUsername: req.params.senderUsername,
};
const messages = await Messages.find({$or:[query,query2]}).exec();
console.log(messages);
res.json(messages);
});
Could there be a better way to do it? I would really like to understand this better.
Thank you #Paweł Antyporowicz for the help :)

How to fix "Can't perform a React state update on an unmounted component"?

I'm building a TODO list and one of the things that it needs to do is delete.
Here is my server.js code
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const cpdRoutes = express.Router();
const PORT = 4000;
let Cpd = require("./cpd.model");
app.use(cors());
app.use(bodyParser.json());
//connects my backend to my mongo database
mongoose.connect('mongodb://127.0.0.1:27017/cpds', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established successfully");
})
cpdRoutes.route('/').get(function(req, res) {
Cpd.find(function(err, cpds) {
if (err) {
console.log(err);
}
else {
res.json(cpds);
}
});
});
//finds the data by id
cpdRoutes.route('/:id').get(function(req, res) {
let id = req.params.id;
Cpd.findById(id, function(err, cpd) {
res.json(cpd);
});
});
//creating data
cpdRoutes.route('/add').post(function(req, res) {
let cpd = new Cpd(req.body);
cpd.save()
.then(cpd => {
res.status(200).json({'cpd': 'New data added successfully'});
})
.catch(err => {
res.status(400).send('Adding new data failed');
});
});
//update data
cpdRoutes.route('/update/:id').post(function(req, res) {
Cpd.findById(req.params.id, function(err, cpd) {
if (!cpd)
res.status(404).send("data is not found");
else
cpd.cpd_date = req.body.cpd_date;
cpd.cpd_activity = req.body.cpd_activity;
cpd.cpd_hours = req.body.cpd_hours;
cpd.cpd_learningStatement = req.body.cpd_learningStatement;
cpd.save().then(cpd => {
res.json('Data updated!');
})
.catch(err => {
res.status(400).send("Update not possible");
});
});
});
// cpdRoutes.route('/delete/:id').post(function(req, res) {
// Cpd.findById(req.params.id, function(err, cpd) {
// if (!cpd)
// res.status(404).send("data is not found");
// else
// cpd.cpd_date = req.body.cpd_date;
// cpd.cpd_activity = req.body.cpd_activity;
// cpd.cpd_hours = req.body.cpd_hours;
// cpd.cpd_learningStatement = req.body.cpd_learningStatement;
// cpd.save().then(cpd => {
// res.json('Data updated!');
// })
// .catch(err => {
// res.status(400).send("Update not possible");
// });
// });
// });
cpdRoutes.route.get('/delete', function(req, res){
var id = req.query.id;
Cpd.find({_id: id}).remove().exec(function(err, expense) {
if(err)
res.send(err)
res.send('Data successfully deleted!');
})
});
app.use('/cpds', cpdRoutes);
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
My delete component:
import React from 'react';
import axios from 'axios';
import { Button } from 'react-bootstrap';
import { Link } from 'react-router-dom';
class DeleteCpd extends React.Component {
constructor(){
super();
this.state={id:''};
this.onClick = this.onClick.bind(this);
this.delete = this.delete.bind(this);
}
// componentDidMount() {
// this.setState({
// id: this.props.cpds.id
// })
// }
componentDidMount() {
axios.get('http://localhost:4000/cpds/'+this.props.match.params.id)
.then(response => {
this.setState({
cpd_date: response.data.cpd_date,
cpd_activity: response.data.cpd_activity,
cpd_hours: response.data.cpd_hours,
cpd_learningStatement: response.data.cpd_learningStatement
})
})
.catch(function (error) {
console.log(error);
})
}
onClick(e){
this.delete(this);
}
delete(e){
axios.get('http://localhost:4000/cpds/'+this.props.match.params.id)
.then(function(response) {
});
}
render(){
return (
<Button onClick={this.onClick}>
<Link to={{pathname: '/', search: '' }} style={{ textDecoration: 'none' }}>
<span className="glyphicon glyphicon-remove"></span>
</Link>
</Button>
)
}
}
export default DeleteCpd;
and my App.js:
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import CreateCpd from "./components/create-cpd.component";
import EditCpd from "./components/edit-cpd.component";
import CpdsList from "./components/cpds-list.component";
import DeleteCpd from "./components/cpds-delete.component";
class App extends Component {
render() {
return (
<Router>
<div className="container">
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<Link to="/" className="navbar-brand">MERN-Stack Cpd tracker App</Link>
<div className="collpase navbar-collapse">
<ul className="navbar-nav mr-auto">
<li className="navbar-item">
<Link to="/" className="nav-link">Data List</Link>
</li>
<li className="navbar-item">
<Link to="/create" className="nav-link">Create Cpd data</Link>
</li>
</ul>
</div>
</nav>
<br/>
<Route path="/" exact component={CpdsList} />
<Route path="/edit/:id" component={EditCpd} />
<Route path="/delete/:id" component={DeleteCpd} />
<Route path="/create" component={CreateCpd} />
</div>
</Router>
);
}
}
export default App;
This is the error my getting:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in CpdList (created by Context.Consumer)
What I'm trying to do is delete via id. What am I doing wrong?
This is my CPDList:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
// import { CSVLink } from "react-csv";
// import DeleteCpd from './cpd_delete.component';
const Cpd = props => (
<tr>
<td>{props.cpd.cpd_date}</td>
<td>{props.cpd.cpd_activity}</td>
<td>{props.cpd.cpd_hours}</td>
<td>{props.cpd.cpd_learningStatement}</td>
<td>{props.cpd.cpd_evidence}</td>
<td>
<Link to={"/edit/"+props.cpd._id}>Edit</Link>
</td>
<td>
<Link to={"/delete/"+props.cpd._id}>Delete(not working yet)</Link>
</td>
</tr>
)
export default class CpdList extends Component {
constructor(props) {
super(props);
this.state = {
cpds: [],
// csvData:[
// {
// "date": ""
// },
// {
// "activity": ""
// },
// {
// "hours": ""
// },
// {
// "learningStatement": ""
// },
// {
// "evidence": ""
// }
// ]
};
};
// exportCsv()
// {
// var csvRow=[];
// }
componentDidMount() {
axios.get('http://localhost:4000/cpds/')
.then(response => {
this.setState({ cpds: response.data });
})
.catch(function (error){
console.log(error);
});
};
componentDidUpdate() {
axios.get('http://localhost:4000/cpds/')
.then(response => {
this.setState({ cpds: response.data });
})
.catch(function (error){
console.log(error);
});
}
cpdList() {
return this.state.cpds.map(function(currentCpd, i){
return <Cpd cpd={currentCpd} key={i} />;
});
}
render() {
return(
<div>
<h3>Cpd Data List</h3>
<table className="table table-striped" style={{ marginTop: 20 }} >
<thead>
<tr>
<th>Date</th>
<th>Activity</th>
<th>Hours</th>
<th>Learning Statement</th>
<th>Evidence</th>
</tr>
</thead>
<tbody>
{ this.cpdList() }
</tbody>
</table>
{/* <CSVLink data={csvData}
filename={"db.csv"}
color="primary"
style={{float: "left", marginRight: "10px"}}
className="btn btn-primary"
>Download .CSV
</CSVLink> */}
</div>
)
}
};
please ignore the commented out code still working on that.

Not able to re-render the page after updating redux state

Here i am getting the list of google drive files in '/dashboard/gdrive'. There is one more event of uploading a new file. On uploading the redux state shows that the new file is stored in state but whil re-rendering i am not able to access the store states.
Here is the codeblock
import React, { Component } from 'react';
import PropTypes from "prop-types";
import {connect} from "react-redux";
import {logoutUser} from "./../../actions/authActions.js";
import {syncCloud} from "./../../actions/cloudActions.js";
import {uploadFile} from "./../../actions/cloudActions.js";
class Gdrive extends Component {
constructor(){
super();
this.state={
file: null
}
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.handleCancelEvent = this.handleCancelEvent.bind(this);
}
onChange(e){
this.setState({
file: e.target.files[0]
});
}
onSubmit(e){
e.preventDefault();
const data = new FormData();
data.append('filename', this.state.file);
this.props.uploadFile(data);
}
handleCancelEvent(){
this.setState({
file: null
})
}
render() {
return (
<div>
<table>
<thead>
<tr><th>fileid</th><th>filename</th></tr>
</thead>
<tbody>
{this.props.cloud.files.data.map(file =>(
<tr>
<td>{file.id}</td>
<td>{file.name}</td>
</tr>
))}
</tbody>
</table>
<fieldset>
<form noValidate onSubmit={this.onSubmit}>
<div>
<label>filename</label>
<input type="file" onChange={this.onChange} name= "filename"></input>
</div>
<div>
<button type="submit">Upload</button>
<button onClick={this.handleCancelEvent}>Cancel</button>
</div>
</form>
</fieldset>
</div>
)
}
}
Gdrive.propTypes = {
logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth,
cloud: state.cloud
});
export default connect(
mapStateToProps,
{ logoutUser, syncCloud, uploadFile }
)(Gdrive);
and here is uploadFile action
export const uploadFile = (file) => dispatch => {
axios.post('/gdrive/upload', file)
.then(rslt => {
dispatch({
type: UPLOAD_FILE,
payload: {id: rslt.data.fileid, name: rslt.data.filename}
})
})
.catch(err => {
dispatch({
type: GET_ERRORS,
payload: err
})
});
}
Here is the reducer
import {SYNC_CLOUD, UPLOAD_FILE} from './../actions/types';
const initialState = {
files: {}
};
export default function(state=initialState, action){
switch(action.type){
case SYNC_CLOUD:
return{
...state,
files: action.payload
};
case UPLOAD_FILE:
return{
...state,
files: state.files.data.concat(action.payload),
};
default:
return state;
}
}
error screenshot
I think your reducer is wrongly mapped.The key here is to declare inital state as empty files rather empty object. And also concatinating the existing array with the response from api(payload).
Change ur reducer to something like this:
import {SYNC_CLOUD, UPLOAD_FILE} from './../actions/types';
const initialState = {
files: []
};
export default function(state=initialState, action){
switch(action.type){
case SYNC_CLOUD:
return{
...state,
files: action.payload
};
case UPLOAD_FILE:
return{
[...state, action.payload],
};
default:
return state;
}
}
And change the render function to
<tbody>
{this.props.cloud.files.map(file =>(
<tr>
<td>{file.id}</td>
<td>{file.name}</td>
</tr>
))}
</tbody>
mapDispatchToProps parameter to connect needs to be a function. Either do something like this
const mapDispatchToProps= dispatch => bindActionCreators(
{ logoutUser, syncCloud, uploadFile },
dispatch
)
Or, in pass null as your mapDispatchToProps and in your component use the action creator like this this.props.dispatch(uploadFile(data))

How to get the data from mongodb using node.js andfront-end as angular

I am currently learning node.js and creating test application using angular so in that i need to retrieve data stored in Mongodb below i have written query to get mongodb data using node.js but unable to get data so what is the exact procedure for changes need to be done in query.
In Html(component in angular):
<div class="col-md-12">
<div class="container">
<table class="table mar-top-20">
<thead class="thead-dark">
<tr>
<th>Date</th>
<th>Client Name</th>
<th>Client Email</th>
<th>Client Password</th>
<th>Action/Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{userDetails.added_on}}</td>
<td>{{userDetails.username}}</td>
<td>{{userDetails.uemail}}</td>
<td>{{userDetails.upassword}}</td>
<td>Show Detail</td>
</tr>
</tbody>
</table>
</div>
</div>
In TS file(component in angular):
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup , Validators } from '#angular/forms';
import { DataService } from '../../../services/data.service';
import { AccountService } from '../../../services/account.service';
import { Router } from '#angular/router';
// import { Client } from '../../../client';
#Component({
selector: 'app-manage-users',
templateUrl: './manage-users.component.html',
styleUrls: ['./manage-users.component.css'],
})
export class ManageUsersComponent implements OnInit {
userDetails: any;
rForm: FormGroup;
post:any;
username: String = '';
uemail: String = '';
upassword: String = '';
constructor(private router: Router,private fb:FormBuilder,private dataService: DataService, private accountService: AccountService) {
this.rForm = fb.group({
'username':['', Validators.required],
'uemail':['', Validators.required],
'upassword': [ '', Validators.required ]
});
}
ngOnInit() {
//Getting user using userId
this.accountService.getUser({ userId: localStorage.getItem('userId') }).subscribe(
response => {
console.log(response);
this.userDetails = JSON.parse(response);
},
err => {
console.error('User Not found');
})
}
}
accountService.ts:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { DataService } from './data.service';
#Injectable()
export class AccountService {
public apiPath: string;//Api URL where we need to send our data & perform related operations
constructor(ds: DataService, private http: HttpClient) {
this.apiPath = ds.apiPath;
}
getUser(user) {//Getting User with userId
return this.http.post(this.apiPath + 'user/getUser', user, { responseType: 'text' });
}
}
UserController.js:
userRouter.post('/getUser', (req, res) => {
var user = {
_id: req.body.userId,
};
Collections.user.findOne(user, function (err, result) {
if (err) return res.status(500).send("There was a problem finding the user");
if (result) {
res.status(200).send(result);
} else {
res.status(500).send("User Not Found with Details: " + JSON.stringify(user));
}
});
});
My database name is testdb and collection name is users

Resources