How to pass parameters from angular4 component to express API - node.js

I am working for mean stack application. I am able to connect express api and angular component, but i want to pass parameters to the api service.
Please find the code below for clearer idea,
Component Code
constructor(private _dataService: DataService){
var parametervalue = "Monthly";
this._dataService.getexternalSourceDetailFiltered().subscribe((data) => {
this.source.load(data);
});}
DataService Code
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class DataService {
result;
constructor(private _http: Http) { }
getStudents(){
return this._http.get('/external_sources').map(result =>
this.result = result.json().data);
}
getexternalSourceDetail(){
return this._http.get('/external_sources_details').map(result =>
this.result = result.json().data);
}
getexternalSourceDetailFiltered(){
return this._http.get('/external_sources_details').map(result =>
this.result = result.json().data);
}
}
Express API Code
router.get('/external_sources_details_filtered',(req,res) =>{
connection((db) => {
var intId = parseInt(0);
var query ={'frequency.Monthly':{$exists:true}};
var projection = {_id:0,sourceID:1,SourceName:1, Outstanding:1};
db.collection('external_sources').find(query).project(projection).
toArray().then((external_sources_details_filtered) => {
response.data = external_sources_details_filtered;
res.json(response);
})
})
})
How would i pass parametervalue from the component so that i can use it in express API to pass parameter to call mongodb using dynamic parameter

SOLUTION: Being totally new i searched around and found a solution:
i used URLSearchParams to set the parameter to pass through the express API.
Here is the the code for better understanding,
Component Code:
constructor(private _dataService: DataService){
var param = new URLSearchParams();
param.append('frequency','Monthly');
this._dataService.getexternalSourceDetailFiltered(param).subscribe((data) => {
this.source.load(data);
});
}
Data Service Code
getexternalSourceDetailFiltered(parameterValue:any ){
return this._http.get('/external_sources_details_filtered',
{
params:parameterValue}).map(result => this.result = result.json().data);
}
Express API js Code
router.get('/external_sources_details_filtered',(req,res) =>{
let parameterValue;
connection((db) => {
if(req.query.frequency != '')
{
parameterValue = String( 'frequency.'+ req.query.frequency);
}
else
{
parameterValue = String( 'frequency');
}
console.log(parameterValue);
var query = {[parameterValue] :{$exists:true}};
var projection = {_id:0,sourceID:1,SourceName:1, Outstanding:1};
db.collection('external_sources').find(query).project(projection).toArray().then((external_sources_details_filtered) => {
response.data = external_sources_details_filtered;
res.json(response);
})
})

Related

TypeError: Cannot read properties of undefined (reading 'length') while using Interceptor

I have the following Angular and Node JS as follows
Interceptor
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "#angular/common/http";
import { Injectable } from "#angular/core";
import { Observable } from "rxjs";
import { AuthService } from "../Services/auth.service";
#Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService : AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
//console.log(this.authService.getAuthToken())
const authToken = this.authService.getAuthToken();
const authRequest = req.clone({
headers: req.headers.set("Authorization", authToken)
});
console.log("authRequest");
return next.handle(authRequest);
}
}
service
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { api_url } from '../Models/global-url.model';
import { LoginModel } from '../Models/login_details.model';
import { ResponseFromServer } from '../Models/response.model';
#Injectable({
providedIn: 'root'
})
export class AuthService {
private token : string;
//Password is asish for all users
constructor(private http: HttpClient) { }
checkUserLogin(loginDetails: LoginModel) {
console.log(loginDetails);
this.http.post<{response: any}>(api_url+"login/loginUser", loginDetails).subscribe((result: ResponseFromServer) => {
console.log(result.token);
this.token = result.token;
console.log(this.token);
});
}
getAuthToken() {
return this.token;
}
}
User Defined Middleware in Node JS :-
const jwt = require('jsonwebtoken');
const s_token = require('../tokens/auth-token');
//const authFunction = (req, res, next) => {
module.exports = (req, res, next) => {
console.log(req);
var message = '';
try {
const token = req.headers.authorization;
console.log(token);
jwt.verify(token, s_token);
next();
} catch (err) {
message = "Auth Failed";
console.log(err); //JsonWebTokenError: Error jwt must be provided => user is not logged in
res.status(401).json(message);
// res.json(message); //Check the error message that occurs in browser console, while using this without status
}
}
login.js in Node Router :-
router.post('/loginUser', async (req, res, next) => {
const loginDetails = req.body;
console.log(loginDetails);
var { userId, stored_password,userEmailId,token,status_code } = '';
var message = '';
var response = '';
//console.log(loginDetails);
query = `SELECT * FROM tbl_users WHERE (tum_email = $1 OR tum_mobile = $1)`;
params = [loginDetails.username];
// await db.query(query, params, (err, result) => {
// if(err) {
// console.log(err);
// response = 'f0';
// message = "Internal Server Error. Please reload the page and try again.";
// } else if(result.rows.length) {
// //console.log(result.rows.length);
// userId = result.rows[0].tum_email;
// password = result.rows[0].tum_password;
// response = 's1';
// message = "";
// } else {
// response = 'f1';
// message = "User with the given user id does not exist. Please register here";
// }
// });
try {
const result = await db.query(query, params);
if(result.rowCount == 0 ) {
response = 'f1';
message = "User with the given user id does not exist. Please register here";
} else {
userId = result.rows[0].tum_id;
userEmailId = result.rows[0].tum_id;
stored_password = result.rows[0].tum_password;
try {
if ((await argon2.verify(stored_password, loginDetails.password))) {
//password matches
response = 'success';
const session_data = {
userId: userId,
email: userEmailId
}
token = jwt.sign(session_data, s_token, {expiresIn:'1hr'});
//console.log(token);
} else {
response = 'f2';
message = "Entered password is wrong. Please enter the correct password, or reset it";
}
} catch (err) {
console.log(err);
response = 'f0';
message = "Internal Server Error. Please reload the page and try again, or contact an Administrator";
}
}
} catch (err) {
console.log(err);
response = 'f0';
message = "Internal Server Error. Please reload the page and try again, or contact an Administrator";
}
const json_object = {
token: token,
response: response,
message:message
}
if(token != '') {
status_code = 200;
} else {
status_code = 401;
}
res.status(status_code).json(json_object);
//console.log("response ="+response+" & message = "+ message);
});
login.component.ts
import { Component, OnInit } from '#angular/core';
import { NgForm } from '#angular/forms';
import { AuthData } from 'src/app/Models/auth_data.model';
import { LoginModel } from 'src/app/Models/login_details.model';
import { ResponseFromServer } from 'src/app/Models/response.model';
import { AuthService } from 'src/app/Services/auth.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
isSubmitted = false;
isValid = true;
isLoading = false;
response_from_server = new ResponseFromServer();
constructor(private authService: AuthService) {
}
ngOnInit(): void {
this.response_from_server.response = 's1';
}
loginUser(loginData: NgForm) {
this.isSubmitted = true;
if(loginData.invalid) {
this.isValid = false;
//console.log("Validation Errors");
return;
}
const loginDetails : LoginModel = {
username : loginData.value.username,
password: loginData.value.password
}
this.authService.checkUserLogin(loginDetails);
}
}
Whenever I try to login , the error TypeError: Cannot read properties of undefined (reading 'length') is thrown.
The data is not even sent to the server side. It is stuck before return next.handle(authRequest);.
I tried console.log() almost everywhere to see where I am getting the mistake, and to which part, the data movement is getting done. Looks like the email and password are not even going through, to the Node JS server. Using console.log(result.token) in login.service.ts does not have any value.
Where am I going wrong ?
The problem is most likely happening because your trying to add the Authorization header before the user is logged-in.
In that situation authToken is undefined and you are assigning it to the header anyways.
You could solve it just adding a guard in your intercept method to first check if you have an authToken before attaching it to the request.
intercept(req: HttpRequest<any>, next: HttpHandler) {
const authToken = this.authService.getAuthToken();
if(!authToken) { // <--- not logged-in skip adding the header
return next.handle(req);
}
const authRequest = req.clone({
headers: req.headers.set("Authorization", authToken)
});
return next.handle(authRequest);
}
Cheers

How to use a promised function in a react app

I'm trying to implement Bullet train API in a React web app. According to their node client documentation, I have setup the following function:
export const isFeatureEnabled = async (nameOfTheFeature) => {
return new Promise((resolve) => {
bulletTrain.init({
environmentID: BULLET_TRAIN_ENV_ID
});
bulletTrain.hasFeature(nameOfTheFeature)
.then((featureFlag) => {
if (featureFlag[nameOfTheFeature].enabled) {
resolve(true);
}
})
.catch(err => resolve(false));
});
}
This is called in regular components like this:
render() {
return (<div>{await isFeatureEnabled('feature1') && <p>feature1 is enabled</p>}</div>)
};
which throws this:
Parsing error: Can not use keyword 'await' outside an async function
If we add the async keyword, with a proper return statement:
async render() {
return (<div>{await isFeatureEnabled('feature1') && <p>feature1 is enabled</p>}</div>)
};
Then it throws:
Your render method should have return statement
So what is the correct way to use this promised function inside a react app?
I would suggest you not to use await keyword in render instead use componentDidMount and constructor for this and use state object to check:
constructor(props){
super(props);
this.state = { isFeatEnabled: false };
}
componentDidMount(){
this.setState({isFeatEnabled:isFeatureEnabled('feature1')})
}
Now in the render:
render() {
return (<div>{this.state.isFeatEnabled && <p>feature1 is enabled</p>}</div>)
};
And remove the async from the method.
call function isFeatureEnabled inside an async function during mount (before/after your wish)
example -
export const isFeatureEnabled = async (nameOfTheFeature) => {
return new Promise((resolve) => {
bulletTrain.init({
environmentID: BULLET_TRAIN_ENV_ID
});
bulletTrain.hasFeature(nameOfTheFeature)
.then((featureFlag) => {
if (featureFlag[nameOfTheFeature].enabled) {
resolve(true);
}
})
.catch(err => resolve(false));
});
}
...
componentDidMount() {
this.checEnabled();
}
...
const checkEnabled = async () => {
const flag = await isFeatureEnabled('feature1');
this.setState({f1enabled: flag});
}
...
render() {
return (<div>{this.state.f1enabled ? <p>feature1 is enabled</p> : null}</div>)
}
If isFeatureEnabled is in the same file keep it outside class component or else keep it in another file and export the function.
You can't use promise at there, the proper way:
import React, { useEffect, useState } from 'react'
import bulletTrain from '../somewhere'
import BULLET_TRAIN_ENV_ID from '../somewhere'
export default function featureComponent({ featureName }) {
const [featureEnabled, setFeatureEnabled] = useState(false)
useEffect(() => {
bulletTrain.init({
environmentID: BULLET_TRAIN_ENV_ID
})
bulletTrain
.hasFeature(featureName)
.then(featureFlag => {
if (featureFlag[featureName].enabled) {
setFeatureEnabled(true)
}
})
.catch(err => setFeatureEnabled(false))
}, [featureName])
return <div>{featureEnabled && <p>{featureName} is enabled</p>}</div>
}
Append isFeatureEnabled function re-use answer below:
import React, { useEffect, useState } from 'react'
import isFeatureEnabled from '../somewhere'
export default function featureComponent({ featureName }) {
const [featureEnabled, setFeatureEnabled] = useState(false)
useEffect(() => {
const checkAndSetEnabled = async () => {
const enabled = await isFeatureEnabled(featureName)
setFeatureEnabled(enabled)
}
checkAndSetEnabled()
}, [featureName])
return <div>{featureEnabled && <p>{featureName} is enabled</p>}</div>
}

Angular HTTP GET not hitting Express Route

My Angular HTTP GET Request indside clearNotifications() in notification.service.ts not hitting Express Route routes/notifications.js. I am calling clearNotifications() from a component called app.component.ts. I am using Angular 7+
routes/notifications.js
const router = require('express').Router();
//Additional modules
// const db = require('../config/database');
// const notificationModel = require('../models/notifications');
//Test connection
// db.authenticate().then(() => {
// console.log('Connection has been established successfully.');
// }).catch(err => {
// console.error('Unable to connect to the database:', err);
// });
//Clear all notifications
router.get('/clear', (req, res, next) => {
console.log('clear');
// notificationModel.destroy({});
});
module.exports = router;
notification.service.ts
import { Injectable } from '#angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class NotificationService {
uri = 'http://localhost:5000';
private socket = io(this.uri);
constructor(private http: HttpClient) { }
getNotification() {
let observable = new Observable<{ string: String, number: String }>(observer => {
this.socket.on('notification', (data) => {
observer.next(data);
});
// return () => { this.socket.disconnect(); }
})
return observable;
}
clearNotifications() {
return this.http.get(`${this.uri}/notifications/clear`);
}
}
app.component.ts
import { Component } from '#angular/core';
import { NotificationService } from './notification.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [NotificationService]
})
export class AppComponent {
title = 'client';
string: String;
number: String;
notificationArray: Array<{ string: String, number: String }> = [];
constructor(private notificationService: NotificationService) {
this.notificationService.getNotification().subscribe(data => {
this.notificationArray.push(data);
});
}
clearNotifications() {
this.notificationArray = [];
this.notificationService.clearNotifications();
}
}
You should be doing this: Check the basic routing on express
var express = require('express');
var app = express();
app.get('/clear', (req, res) => {
console.log('clear');
res.send(success);
// notificationModel.destroy({});
});
Also make sure to subscribe to the service method from your component. If you do not subscribe the observables won't execute.
Where are you calling clearNotifications from?
subscribe to clearNotifications in component and this will work:
this.notificationService.clearNotifications().subscribe( (data) => { ..})
As a publisher, you create an Observable instance that defines a subscriber function. This is the function that is executed when a consumer calls the subscribe() method. The subscriber function defines how to obtain or generate values or messages to be published
In angular, http request returns observable, so you need to subscribe. If there aren't any subscriber to the observable, it wont be executed. Try
clearNotifications() {
return this.http.get(`${this.uri}/notifications/clear`)
.subscribe(data => //your callback function,
error => // your error handler,
complete => // any after completion task);
}

How to use Backend Object in FrontEnd TypeScript (MEAN Stack)

Using MongoDB, express.js, angular4, node.js
A string I retrieve is well retrieved, but not the same as a full object...
account.service.ts (full, )
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
const jwtDecode = require('jwt-decode');
import { User } from '../../models/user.model';
import { AuthService } from './auth.service';
#Injectable()
export class AccountService {
constructor(private http: HttpClient,
private authService: AuthService) {}
user: any[];
currentUser() {
if(this.authService.isAuthenticated()){
const token = localStorage.getItem('token');
const decoded = jwtDecode(token);
return decoded.user;
}
};
getProfile() {
const id = this.currentUser();
return this.http.get("http://localhost:3000/user/" + id).
map(
(response: Response) => {
const data = response.json();
return data;
}
)
.catch(
(error: Response) => {
console.log(error);
return Observable.throw(error.json());
}
)
}
user-profile.component.ts
export class UserProfileComponent implements OnInit {
id: string;
user: any;
constructor(private account: AccountService) {}
ngOnInit() {
this.id = this.account.currentUser();
this.user = this.account.getProfile()
.subscribe(user => {
this.user = user;
return this.user;
});
}
logUser() {
console.log(this.id);
console.log(this.user);
}
}
user-profile.component.html
<p>{{user}}</p>
<p>User with ID {{id}} Loaded</p>
<a (click)="logUser()">Log User Test</a>
HTML file shows:
[object Object]
User with ID 59ca916323aae527b8ec7fa2 Loaded
What I get from clicking "log User" link is the retrieved ID string and the user object:
59ca916323aae527b8ec7fa2
[{...}] //clicking this reveals all of the object's details.
But I can't make that step of getting those details and presenting them in the HTML as I successfully managed with the ID... I mean, {{user.anything}} doesn't fetch the user's data as it should
May I have some assistance?
Change your getProfile() to,
getProfile() {
const id = this.currentUser();
return this.http.get("http://localhost:3000/user/" + id).
map(
(response) => response.json()
)
.catch(
(error: Response) => {
console.log(error);
return Observable.throw(error.json());
}
)
}
Also, in ngOnInit() change this one,
this.user = this.account.getProfile()
.subscribe((user) => {
this.user = user;
});
See if it gives you the right output.
EDIT
Change this one,
this.user = this.account.getProfile()
.subscribe((user) => {
this.user = JSON.parse(JSON.stringify(user));
});
EDIT-2
this.user = this.account.getProfile()
.subscribe((user) => {
this.user = JSON.stringify(user);
this.userObj = JSON.parse(JSON.stringify(user));
// also try, this.userObj = user; if above line didn't work
});
Define another property in component as ,
userObj: any;
Refer to the object in template as this
{{ userObj[0]?.email }}

Angular2 / NodeJS file uploader. req.files not present

I am currently developing an application in Angular2 which is wrapped by in a NodeJS instance which talks to an API. I am currently implementing some file upload functionality and cannot get a function which captures the API file upload request in the NodeJS layer to show that it is catching the files. There is no 'files' property on the 'req' object.
Here is my code:
import { Component } from "#angular/core";
import { routes } from "../../../routes";
import { FilesService } from "../../../services/files.service";
#Component({
selector : 'file-upload',
moduleId : module.id,
templateUrl : '/app/views/files/file-upload.html',
})
export class FileUploaderDirective {
private _filesToUpload: Array<File> = [];
constructor(
private _filesService: FilesService
) {
}
fileChangeEvents(fileInput: any) {
this._filesToUpload = <Array<File>> fileInput.target.files;
}
upload() {
this._filesService.sendFile(routes.api.files, [], this._filesToUpload)
.then((result) => {
console.log(result);
}, (error) => {
console.log(error);
});
}
}
MY file upload Angular2 service:
import { Injectable } from "#angular/core";
import { Observable } from "rxjs";
#Injectable()
export class FilesService {
constructor() {
}
sendFile(url: String, vars: Array<String>, files: File[]): Promise<any> {
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
}
The NodeJS route that catches the api request and forwards it to a controller function in NodeJS:
router.post('/upload', function(req, res, next) {
filesRoutesControllerObjectInstance.upload(req, res, next);
});
And the function which is supposed to catch the request and send the files to the API:
var ApiBase_RequestLayer = require('../ApiBase_RequestLayer'),
Config = require(global.appRoot + '/Config'),
util = require('util');
function Files() {
Files.super_.call(this);
this.requestBaseUrl = Config.brain.url + '/upload';
}
Files.prototype.upload = function(req, res) {
if(req) {
}
};
util.inherits(Files, ApiBase_RequestLayer);
module.exports = Files;
When I debug the request there is no files present on the request when I debug the 'req' object in the NodeJS 'uoload' route and the controller. As you can see I am attempting to send them using the FormData Angular2 functionality. Can anyone see what I am doing wrong here.

Resources