parse xml to json and subscribe with Angular4 - json

I'm trying to convert an XML string to JSON by using xml2js, then i need to send and subscribe the result in another component.
getLastWeekSnow = function(){
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append("Authorization", "Basic " + btoa('user' + ":" + 'password'));
headers.append('Content-Type' , 'application/x-www-form-urlencoded');
return this.http.get(`${this.APIUrl}`, {headers:headers})
.map(res => {
xml2js.parseString( res.text(), function (err, result) {
console.dir(result); //Prints JSON object!
});
})
.subscribe(data => {
console.log(data); //Undefined !
});
}
so the console.dir(reults) gives me back what i need but in the subscribe (console.log(data)) i get undefined.
Why am i getting undefined in the subscribe , but gets the right Object in the .map ?

Make sure to return your data, otherwise it cannot subscribe
getLastWeekSnow = function(){
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append("Authorization", "Basic " + btoa('user' + ":" + 'password'));
headers.append('Content-Type' , 'application/x-www-form-urlencoded');
return this.http.get(`${this.APIUrl}`, {headers:headers})
.map(res => {
let data;
xml2js.parseString( res.text(), function (err, result) {
console.dir(result); //Prints JSON object!
data = result
});
return data;
})
.subscribe(data => {
console.log(data); //Undefined !
});
}

Related

How to extract key and value from json in fetch method in React Native?

I'm new in React Native. I would like to extract a value from json with fetch to do a simple test to begin. But I don't understand, how to select a particular key from Json. Always, I have undefined return. I tried to modify my code with this post but it doesn't work. I tried to parse before but he didn't want because it's already an object.
This is my code:
checkLogin = () => {
const { name } = this.state;
const { surname } = this.state;
fetch('https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=' + name + '%20' + surname, {
method: 'GET',
}).then((response) => response.json())
.then((responseJson) => {
if (responseJson.ind == 'Individu non trouv\u00e9 !') {
alert("Id incorrect")
}
else {
alert("Id correct");
}
alert(JSON.stringify(responseJson.ind))
}).catch((error) => {
console.error(error);
});
}
This is my JSON format:
[{"iuf":"1366701","ind":"LEBRUN L\u00e9o (2000) H FRA - CN BEAUPREAU","sex":"#1e90ff","clb":"CN BEAUPREAU"}]
I know my request work because when I run this code alert(JSON.stringify(responseJson)).It return the entire json. So I don't know, how to resolve the undefined return.
Regards
Your json is an array, you either need to loop through it if there is multiple items inside, or just use responseJson[0] to read it. So if you want to read your json, your code would look like this :
const checkLogin = () => {
const { name } = this.state;
const { surname } = this.state;
fetch(
"https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=" +
name +
"%20" +
surname,
{
method: "GET"
}
)
.then(response => response.json())
.then(responseJson => {
// Since you have only one object inside your json, you can read the first item with 'responseJson[0]'.
if (responseJson[0].ind == "Individu non trouv\u00e9 !") {
alert("Id incorrect");
} else {
alert("Id correct");
}
alert(JSON.stringify(responseJson[0].ind));
// If you have multiple elements inside your responseJson,
// then here is a loop example :
// responseJson.forEach(item => {
// console.log('item ind = ', item.ind);
// });
})
.catch(error => {
console.error(error);
});
};
Use async await.
const checkLogin = async () => {
const { name } = this.state;
const { surname } = this.state;
const request = await fetch(
"https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=" +
name +
"%20" +
surname)
const response = await request.json();
console.log('result from server', response)
}

node js stops working on multiple api request from angular and working after restarting the node app

i am developing an app with node express js and angular js. My angular app makes an api request from node js app server on each route or button click, also a single component or button click may request multiple api to node js app. upon requesting multiple time the data loading is just got stopped and i am not getting result. Also getting status code like 304 and 204.
please check out my api code and subscribe service code.
constroller.js ///express js
getList: async (req, res) => {
try{
const result = await getList(); //from service.js (an sql query)
var serviceCalls = result[0][0];
return res.set({'Content-Type': 'application/json'}).status(200).json({
success: 1,
message: 'Successfully Data Fetched',
data: serviceCalls
});
} catch(e){
return res.json({
success: 0,
message: 'No Data Fetched' + ' ' + e.message,
data: {}
});
}
},
getDetails: async (req, res) => {
try{
const id = req.query.id
const result = await getDetails(id); //from service.js (an sql query)
var serviceCalls = result[0][0];
return res.set({'Content-Type': 'application/json'}).status(200).json({
success: 1,
message: 'Successfully Data Fetched',
data: serviceCalls
});
} catch(e){
return res.json({
success: 0,
message: {text:'No Data Fetched ', errMsg: e.message},
data: {}
});
}
},
getTroubles: async (req, res) => {
try{
const id = req.query.id
const result = await getTroubles(id); //from service.js (an sql query)
var complaintData = result[0][0];
return res.set({'Content-Type': 'application/json'}).status(200).json({
success: 1,
message: 'Successfully Data Fetched',
data: complaintData
});
} catch(e){
return res.json({
success: 0,
message: 'No Data Fetched',
data: []
});
}
},
getLogs: async (req, res) => {
try{
const id = req.query.id
const result = await getLogs(id); //from service.js (an sql query)
var feedbackData = result[0][0];
return res.set({'Content-Type': 'application/json'}).status(200).json({
success: 1,
message: 'Successfully Data Fetched',
data: logs
});
} catch(e){
return res.json({
success: 0,
message: {text:'No Data Fetched ', errMsg: e.message},
data: []
});
}
},
routes //node js express js
app.js
app.use('/serviceCall', serviceCallRoute);
serviceCallRoute
router.get("/getList", getList);
router.get("/getDetails", getDetails);
router.get("/getTroubles", getTroubles);
router.get("/getLogs", getLogs);
angular subscribe to api
getServiceCalls() {
return this.http.get(url + 'serviceCall/getList',this.httpOptions)
.pipe(
map((res: IServiceCall) => {
return res;
}),
catchError(errorRes => {
return throwError(errorRes);
})
);
}
getServiceCallDetails(id):Observable<IServiceCall> {
const params = new HttpParams().set('id', id);
const headers = new HttpHeaders({ 'Content-Type': 'application/json'})
return this.http.get(url + 'serviceCall/getDetails',{headers:headers,params: params})
.pipe(
map((res: IServiceCall) => {
return res;
}),
catchError(errorRes => {
return throwError(errorRes);
})
);
}
getServiceCallTroubles(id) {
const params = new HttpParams().set('id', id);
const headers = new HttpHeaders({ 'Content-Type': 'application/json'})
return this.http.get<IServiceCallTroubles>(url + 'serviceCall/getTroubles',{headers:headers,params: params})
.pipe(
map((res: IServiceCallTroubles) => {
return res;
}),
catchError(errorRes => {
return throwError(errorRes);
})
);
}
getServiceCallLogs(id):Observable<IServiceCallLogs>{
const params = new HttpParams().set('id', id);
const headers = new HttpHeaders({ 'Content-Type': 'application/json'})
return this.http.get<IServiceCallLogs>(url + 'serviceCall/getLogs',{headers:headers,params: params})
.pipe(
map((res: IServiceCallLogs) => {
return res;
}),
catchError(errorRes => {
return throwError(errorRes);
})
);
}
The express js is working well. It is fault in database connection limit.
the DB connection limit was set as 10. So,after 10 api request with sql query. The db connection gets disconnected.

how to fetch large json from a post in angular6/7

I have migrated a piece of code to be able to export data as excel file in angular.
I assume the fact that the json is well formed and send from the server to the angular side. I can see it in the network frame in th browser.
For small json, it's ok but when the size of the json starts to be large, the answer still failed.
This following code corresponding to the service call
exportSynthesis(recordId: number, moduleId: number) {
const body = null;
return this.http.post(this.apiUrl + `/data`
+ `${recordId}/module/${moduleId}`, body,
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response', responseType: 'json' }).pipe(
map((resp: any) => {
return resp.body;
}));
}
and here, its the method which manages the return.
exportSynthesis() {
this.service.exportSynthesis(this.recordId, this.moduleId)
.subscribe(
(exportResult) => { this.exportResult = exportResult; },
err => {
console.log('err:', err);
this.errorHandlerService.handleError('failed', err);
},
() => {
console.log('json:', this.exportResult);
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.exportResult);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '(GEO) ' + this.record.label + ' - name.xlsx';
a.click();
window.URL.revokeObjectURL(url);
a.remove();
});
}
Currently, i do not manage to understand why it still finish in error and I get only "ok" in the console log.
Any idea?
regards
Angular's HttpClientModule default response is a json.
Your problem is that you try to access the body property of the HTTP response, but Angular interprets that as you trying to access the body property in the body of the response.
Remove observe and responseType from your post request and treat the response as a json. It should work.
find:
just need to use text as json
return this.http.post(this.apiUrl + `/geo/v1/synthesis/xls/record/`
+ `${recordId}/module/${moduleId}`, body,
{
headers: headers,
observe: 'response',
responseType: 'text' as 'json'}).
map((resp: any) => {
return resp.body;
});
}

ionic2 Property does not exist on type '{}'

I am getting a json in typescript in ionic framework.
The json is:
{
"result": "success",
"user": {
"loggedIn": true,
"name": "Nulra",
"password": ""
}
}
And I print the data:
console.log("NULRA CHECKING: " + data.result + " " + data.user);
It gives the error:
Typescript Error
Property 'result' does not exist on type '{}'.
Property 'user' does not exist on type '{}'.
auth-service.ts:
login(credentials) {
let opt: RequestOptions;
let myHeaders: Headers = new Headers;
myHeaders.set('Accept', 'application/json; charset=utf-8');
myHeaders.append('Content-type', 'application/json; charset=utf-8');
opt = new RequestOptions({
headers: myHeaders
})
return new Promise((resolve, reject) => {
this.http.get(apiUrl+'login/0/login?email='+credentials.email+'&password='+credentials.password, opt)
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
},(err) => {
reject(err);
});
});
}
In login.ts:
doLogin(){
this.authService.login(this.loginData)
.then(data => {
console.log("NULRA CHECKING: " + data.result + " " + data.user);
}
.catch(err => {
});
}
Anyone know how to deal with it? because the json I confirmed have result and user. Thanks a lot.
when console.log(data):
Try this-
public userData: any = {};
doLogin(){
this.authService.login(this.loginData)
.then(data => {
this.userData = data;
console.log(`NULRA CHECKING: ${this.userData.result} ${this.userData.user}`);
}
.catch(err => {
});
}
Well, I got this solved when I simple called data['result'] instead of data.result;
For me it appeared only when i first executed ionic serve.

get the all feeds data in single array in node.js

i have one doubt in the node js
i need to get the data from the rss feed
for that i install the rss-parser module in it
https://www.npmjs.com/package/rss-parser
let Parser = require('rss-parser');
let parser = new Parser();
(async () => {
let feed = await parser.parseURL('https://www.reddit.com/.rss');
console.log(feed.title);
feed.items.forEach(item => {
console.log(item.title + ':' + item.link)
});
})();
the code was like that
here they are using the async function
to get the data feed for one url
i have lot of urls
i need to loop it and get the feed details in single array
is there any posibility
please tell me is there any thing
i need to get the all feed url details in a single array
I tried as of now this
I tried this code
exports.getRssFeedLinks = () => {
// Setting URL and headers for request
// Return new promise
return new Promise((fulfill, reject) => {
// Do async job
let getSql = 'SELECT * FROM `news_feeds`';
//console.log(updateSql);
connection.query(getSql, (error, results, fileds) => {
if(error) {
reject(error);
}
else {
returnResult = JSON.stringify(results);
fulfill(returnResult);
}
});
})
}
exports.errHandler = function(err) {
console.log(err.message);
}
exports.getRssFeeds = (req, res) => {
let parser = new Parser();
let feedLink;
var dataPromise = this.getRssFeedLinks();
//console.log(dataPromise);
dataPromise.then(JSON.parse, this.errHandler)
.then(function(newFeeds) {
// Do one more async operation here
let feedsList = [];
if(newFeeds && newFeeds.length > 0) {
let feedLinks = [];
newFeeds.forEach(feed => {
feedLinks.push(feed.link);
});
(async () => {
let feeds = await Promise.all(feedLinks.map(parser.parseURL));
//feeds will have array of arrays, each array includes the response feed from each url
feeds = [].concat(...feeds) //if you want to flatten the array
feed.forEach(({item}) => {
console.log(item.title + ':' + item.link)
});
feeds.forEach(feed => {
console.log(feed.title);
feed.items.forEach(item => {
console.log(item.title + ':' + item.link)
});
})
})();
}
if(feedsList.length >0) {
res.send({
"success" : true,
"result" : feedsList
});
}
else {
res.send({
"success" : true,
"message" : "No Record ",
"result" : feedsList
});
}
}, this.errHandler);
}
Errors
(node:5700) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property
'options' of undefined
(node:5700) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
You can use Promise.all to send multiple request.
(async () => {
let feeds = await Promise.all(['https://www.reddit.com/.rss1', 'https://www.reddit.com/.rss2'].map(parser.parseURL));
//feeds will have array of arrays, each array includes the response feed from each url
feeds = [].concat(...feeds) //if you want to flatten the array
feed.forEach(({item}) => {
console.log(item.title + ':' + item.link)
});
//or use loop through each feed
feeds.forEach(feed => {
console.log(feed.title);
feed.items.forEach(item => {
console.log(item.title + ':' + item.link)
});
})
})();