String to array (object) Angular TS 12 - arrays

I have a CSV file (local), converted it to a string, part of the string is like:
44,"3845657"
51,"3847489"
1,"3888510"
79,"3840471"
57,"3864492"
After I receive input number (first value), I want to match it to the second value (string).
so if input is 51, I want to be able to return 3847489.
No headers in the csv.
CSV to string:
fetchData() {
fetch('../../../assets/static/mapping.csv')
.then(response => response.text())
.then(data => {
// Do something with your data
console.log(data);
this.mappingCSV = data;
});
}
outputs:
44,"3845657"
51,"3847489"
1,"3888510"
79,"3840471"
57,"3864492"
Other ways to convert a csv to an array of objects is also welcome, not married with my csv to string method.

I'm using HTTPClient in this example which is a built-in service class available in Angular. Here's how to use HTTPClient of Angular for you to read and know its benefits.
In my .ts file, I split the text-converted csv first for any newline. Then I added a loop in which I split the text by comma and pushed the necessary details to the new csvArray.
export class SampleComponent {
public csvArr: CsvArray[] = [];
constructor(private http: HttpClient) {
this.http.get('assets/csv.csv', {
responseType: 'text'
}).subscribe(
(data) => {
const csvToRowArray = data.split('\n');
console.log(csvToRowArray);
for (let index = 0; index < csvToRowArray.length; index++) {
const row = csvToRowArray[index].split(',');
this.csvArr.push(new CsvArray(parseInt(row[0], 10), row[1]));
}
console.log(this.csvArr);
},
(error) => {
console.log(error);
}
);
}
}
export class CsvArray {
id: number;
text: string;
constructor(id: number, text: string) {
this.id = id;
this.text = text;
}
}
I created a stackblitz so that you can check my implementation.

Related

Angular 10 - Chained Promises on Array Don't Calculate All Properties

I'm new to Angular and TypeScript, and have encountered a problem:
I have an array of objects of type LabObject model: my LabObject model has quite a lot of properties, along with two private properties that are calculated (private _labTest: number and private _vitalSign: number).
I create an array of type LabObject and populate it using a for loop. Naturally, I have noticed that these two calculations don't finish while the loop is still running, because they are quite heavy, so I figured I'd use a promise.
I thought if I ran the loop in the first promise, and then chained two promises after that, one for each calculation, it would force my calculations to finish running before I did anything else with that array.
It seems that I am wrong, as not all array elements wind up with calculated _labTest and _vitalSign, and in some elements either one or both of them are missing.
Here is my method:
createFile() {
let getLabObject = new Promise((resolve, reject) => {
let lab_objects: LabObject[] = [];
for (let i = 0; i < 10; i++) {
let lo = this.createLabObject();
lab_objects.push(lo);
}
resolve(lab_objects);
});
let getLabTest = objects => {
return new Promise((resolve, reject) => {
objects.forEach(item => {
item.CalculateLabTest();
});
resolve(objects);
});
};
let getVitalSign = objects => {
return new Promise((resolve, reject) => {
objects.forEach(item => {
item.CalculateVitalSign();
});
resolve(objects);
});
};
let backend = objects => {
this.http.post('my backend url address', JSON.stringify(objects))
.subscribe(responseData => {
console.log(responseData);
});
}
getLabObject.then(objects => {
return getLabTest(objects);
}).then(objects => {
return getVitalSign(objects);
}).then(objects => {
return backend(objects);
});
}
I get a JSON object that looks something like this:
[{id: 1, name: 'name1'},
{id: 2, name: 'name2', _labTest: 10},
{id: 3, name: 'name3', _vitalSign: 17},
{id: 4, name: 'name4', _labTest: 8, _vitalSign: 6}]
But I would like for the _labTest and _vitalSign to be calculated for each and every one of the elements.
What am I doing wrong?
I don't think you need promises for this. Actually the asynchronous code is probably the cause of the incomplete objects.
What you are looking for is a getter function. This lets you access a method that calculate a value as-if it is a property. So it is always correct and easy to access. Add a function to extract an object from your LabObject and you are ready to submit it to your backend.
Check this StackBlitz
app.component.ts:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
labtest: LabObject[] = [];
ngOnInit() {
this.labtest.push( new LabObject( 2, 8 ) );
this.labtest.push( new LabObject( 2, 5 ) );
this.labtest.push( new LabObject( 34, 1 ) );
this.labtest.push( new LabObject( 10, 1 ) );
}
log() {
const json = this.labtest.map( labtest => labtest.as_object() );
console.log( JSON.stringify(json) );
// instead of logging you want to submit the JSON to your backend to do whatever you wanted to do...
}
}
class LabObject {
constructor(
public type_a_test: number,
public type_b_test: number
) {}
private get _labTests(): number {
return this.type_a_test + this.type_b_test;
}
private get _vitalSign(): number {
return 2;
}
public as_object(): object {
return {
labtests: this._labTests,
vitalsigns: this._vitalSign
}
}
}

How to convert 3 arrays into a single Object in TypeScript

I am working on an Angular project and I am fetching data from this API
Then I do this:
export class ListComponent implements OnInit {
readonly API_URL = 'https://corona.lmao.ninja/countries';
country = [];
cases = [];
deaths = [];
recovered = [];
countriesData: Object;
constructor(private httpClient: HttpClient) { }
ngOnInit() {
this.httpClient.get(this.API_URL).subscribe((data: Array<any>) => {
data = data.filter(c => c.country !== 'World');
data.forEach(y => {
englishToGreek(this.country, y.country);
this.cases.push(y.cases);
this.deaths.push(y.deaths);
this.recovered.push(y.recovered);
});
console.table(this.countriesData);
});
}
}
The englishToGreek() function translates country names from English to Greek, the source code is this:
const lexor = new Map();
lexor.set('World', 'Παγκοσμίος'); // in extreme cases
lexor.set('USA', 'Η.Π.Α / Αμερική');
lexor.set('Spain', 'Ισπανία');
lexor.set('Italy', 'Ιταλία');
lexor.set('France', 'Γαλλία');
lexor.set('Iran', 'Ιράν');
lexor.set('Germany', 'Γερμανία');
lexor.set('UK', 'Ηνωμένο Βασίλειο');
lexor.set('Turkey', 'Τουρκία');
lexor.set('Switzerland', 'Ελβετία');
lexor.set('Netherlands', 'Ολλανδία');
lexor.set('Canada', 'Καναδάς');
lexor.set('Belgium', 'Βέλγιο');
function englishToGreek(pushableObject, countryName) {
pushableObject.push(lexor.get(countryName));
}
How can I combine the 3 arrays this.cases, this.deaths, this.recovered and assign the result to the this.countriesData object?
Just import the lexor map into same component and use the following code to accomplish your task.
data.forEach(y => {
this.country.push({
country: lexor.get(y.country),
cases: y.cases,
deaths: y.deaths,
recovered: y.recovered,
})
});

Pass an Array as a query String Parameter node.js

How can I pass an array as a query string parameter?
I've tried numerous ways including adding it to the path but i'm not able to pull the array on the back end.
If I hard code the array it works fine, but when I try to pass the array from my front end to the backend it does not work properly.
Can anyone point me in the right direction?
FrontEnd
function loadJob() {
return API.get("realtorPilot", "/myTable/ListJobs", {
'queryStringParameters': {
radius,
availableServices,
}
});
BackEnd
import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";
export async function main(event, context) {
const data = {
radius: event.queryStringParameters.radius,
availableServices: event.queryStringParameters.availableServices,
};
// These hold ExpressionAttributeValues
const zipcodes = {};
const services = {};
data.radius.forEach((zipcode, i) => {
zipcodes[`:zipcode${i}`] = zipcode;
});
data.availableServices.forEach((service, i) => {
services[`:services${i}`] = service;
});
// These hold FilterExpression attribute aliases
const zipcodex = Object.keys(zipcodes).toString();
const servicex = Object.keys(services).toString();
const params = {
TableName: "myTable",
IndexName: "zipCode-packageSelected-index",
FilterExpression: `zipCode IN (${zipcodex}) AND packageSelected IN (${servicex})`,
ExpressionAttributeValues : {...zipcodes, ...services},
};
try {
const result = await dynamoDbLib.call("scan", params);
// Return the matching list of items in response body
return success(result.Items);
} catch (e) {
return failure(e.message);
}
}
Pass a comma seperated string and split it in backend.
Example: https://example.com/apis/sample?radius=a,b,c,d&availableServices=x,y,z
And in the api defenition split the fields on comma.
const data = {
radius: event.queryStringParameters.radius.split(','),
availableServices: event.queryStringParameters.availableServices.split(',')
};

Ionic 4: 'Typescript error' in helperService Cannot read property 'length' of undefined at HelperService

Getting error 'Cannot read property 'length' of undefined at HelperService.addCommasToArray' when trying to loop through an array that has been passed as a paramter in a helperService class [Typescript]
I'm really not sure why this is not working - I believe it should be straightforward - all I'm trying to do is pass in an array as a parameter and add a ',' to every value in the array (except the last value)
Here is my HelperService Class method:
export class HelperService {
constructor() { }
/*
* Add commas to every value in the array except for the last value
*/
addCommasToArray(array: Array<any>) : Array<any> {
for (let i = 0; array.length; i++){
array[i] += ", ";
}
return array;
}
}
I then call this method within the ngInit of another ts class
this.helperService.addCommasToArray(this.previousClubs);
Here is the ngInit method
public previousClubs: Array<any>;
constructor(private playersService: PlayersService,private
helperService: HelperService, private route: ActivatedRoute) { }
ngOnInit() {
const playerId: string = this.route.snapshot.paramMap.get('id');
this.playersService.getPlayerDetails(playerId).get()
.then(playerDetailsSnapshot=> {
this.currentPlayerDetails = playerDetailsSnapshot.data();
this.currentPlayerDetails.id = playerDetailsSnapshot.id;
});
/*
* Return Previous Clubs
*/
this.playersService.getPreviousClubs(playerId).get().then(
previousClubsSnapshot =>{
this.previousClubs = [];
previousClubsSnapshot.forEach(snap => {
this.previousClubs.push({
id: snap.id,
name: snap.data().name,
});
return false;
});
});
this.helperService.addCommasToArray(this.previousClubs);
}
so here:
this.playersService.getPreviousClubs(playerId).get().then(
previousClubsSnapshot =>{
this.previousClubs = [];
previousClubsSnapshot.forEach(snap => {
this.previousClubs.push({
id: snap.id,
name: snap.data().name,
});
return false;
});
});
// this line executes without awaiting for .then enclosed scope
this.helperService.addCommasToArray(this.previousClubs);
Basically you call addCommasToArray even before your previousClubs var gets array assigned to it and then gets all its items pushed in. To fix since your method is (.then) async you need to call for this method inside the .then execution scope:
ngOnInit() {
const playerId: string = this.route.snapshot.paramMap.get('id');
this.playersService.getPlayerDetails(playerId).get()
.then(playerDetailsSnapshot=> {
this.currentPlayerDetails = playerDetailsSnapshot.data();
this.currentPlayerDetails.id = playerDetailsSnapshot.id;
});
/*
* Return Previous Clubs
*/
this.playersService.getPreviousClubs(playerId).get().then(
previousClubsSnapshot =>{
this.previousClubs = [];
previousClubsSnapshot.forEach(snap => {
this.previousClubs.push({
id: snap.id,
name: snap.data().name,
});
return false;
});
});
this.helperService.addCommasToArray(this.previousClubs);
}

How to get the values of the subscribed data in angular2

I wrote a injectable service in which i want to return "display" in my data and i done it sucessfully as follows,
export class GetAllList {
str = localStorage.getItem('social');
loc = JSON.parse(this.str);
id = this.loc._id;
private _productUrl = 'http://localhost:3000/getprofiledetails/'+this.id;
constructor(private _http: Http) { }
getList(): Observable<IDetails[]> {
return this._http.get(this._productUrl)
.map((response: Response) => {
return response.json().data.display;
});
}
}
Here i am subscribing to it,
this._profileservice.getList()
.subscribe(
details1 => this.details1 = details1);
console.log("displaystas:"+this.details)
The problem is,my console is displaying undefined?so how can i see my display value in my console?Can anyone suggest me help.Thank you.
You are printing wrong variable (details instead of details1) and you are missing {}:
this._profileservice.getList()
.subscribe(
details1 => {
this.details1 = details1;
console.log("displaystas: " + this.details1)
}

Resources