Angular-6: Convert string to array of a custom object - javascript

I have this produced string:
string str = [{"id":1,"name":"Angular"},{"id":2,"name":"SpringBoot"}]
I'd like to convert it to an array of Objects to have that:
listexps: Expertise[];
listexps = [{"id":1,"name":"Angular"},{"id":2,"name":"SpringBoot"}];
And Expertise class is
export class Expertise
{
id: number;
name: string;
}
I tried that:
let array = str .replace('[{','').replace('}]','').split("},{").map(String);
but that didn't resolve my problem, I got:
"id":1,"name":"Angular","id":2,"name":"SpringBoot"
instead of
[{"id":1,"name":"Angular"},{"id":2,"name":"SpringBoot"}];
Have you please any idea about solving that ?.
Big thanks.

What you need is JSON.parse; it converts string to an object;
relevant ts:
import { Component } from '#angular/core';
export class Expertise {
id: number;
name: string;
}
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
strIntoObj: Expertise[];
constructor() {
let str: string = '[{"id":1,"name":"Angular"},{"id":2,"name":"SpringBoot"}]';
this.strIntoObj = JSON.parse(str);
console.log(this.strIntoObj);
}
}
complete working stackblitz here

Related

Angular: How can i push an observable to a list

I get an Error message that i cant push an undefined variable to my list.
This is my code in the component.ts
for (const file of this.allFiles) {
this.uploadFileService
.validate(file)
.subscribe( valid => {
this.validList.push(valid);
})
}
This is my Service:
validate(file: File): Observable<boolean> {
const data: FormData = new FormData();
data.append('file', file);
return this.http.post<boolean>(`${this.url}/validate`,data);
}
How can I push to the list?
You will get this error if you do not initialize the array ([]) first before pushing. Please declare the variable validList: Array<any> = [] at the top of the component before pushing data inside.
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit{
name = 'Angular';
validList: Array<any> = [];
ngOnInit() {
this.validList.push(true);
}
}
Issue replicated stackblitz
Working stackblitz

Array of component with a constructor and HTML and CSS files. error NG2003. ngFor

My Problem: I created a CardComponent acts like a card view with css and html and has a constructor.
I want to use it in a cards array (of its type). I use service to store the cards' data.
home comp. is using the service and loop over with ngFor, This is the code.. and below is the error I get...
Is there another way of using this so it will work?
card.component.ts:
import { Component } from '#angular/core';
#Component({
selector: 'app-card',
templateUrl: './card.component.html',
styleUrls: ['./card.component.css']
})
export class CardComponent{
imageSrc : string;
title : string;
constructor(imgSrc : string, title : string) {
this.imageSrc = imgSrc;
this.title = title;
}
ngOnInit(): void {
}
cards.service.ts:
import { CardComponent } from './card/card.component';
export class CardsService{
ctgryCards : CardComponent[] = [
new CardComponent("https://cdn3.iconfinder.com/data/icons/outline-amenities-icon-set/64/Beauty_Saloon-512.png", "Beauty"),
new CardComponent("https://www.pinclipart.com/picdir/middle/391-3917890_get-business-value-from-sustainable-data-electronics-icon.png", "Electronics")
];
getAllCtgryCards(){
return this.ctgryCards.slice();
}
}
home.component.ts:
import { Component, OnInit } from '#angular/core';
import { CardComponent } from '../card/card.component';
import { CardsService } from '../cards.service';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
categoryCards : CardComponent[] = [];
constructor(private cardsServ : CardsService) { }
ngOnInit(): void {
this.categoryCards = this.cardsServ.getAllCtgryCards();
}
}
home.component.html:
<app-card *ngFor = "let card of categoryCards"></app-card>
Error NG2003:
ERROR in src/app/card/card.component.ts:12:15 - error NG2003: No
suitable injection token for parameter 'imgSrc' of class
'CardComponent'. Found string
constructor(imgSrc : string, title : string) {
In card.component.ts:
Update the constructor to be
//import { Inject } from '#angular/core';
constructor(#Inject(String) private imgSrc : string, title : string)
OR
//import { Inject } from '#angular/core';
constructor(#Inject('imgSrc') private imgSrc : string, title : string)
According to https://angular-2-training-book.rangle.io/di/angular2/inject_and_injectable ; #Inject() is a manual mechanism for letting Angular know that a parameter must be injected. #Inject decorator is only needed for injecting primitives.
The primitive types are number, string, boolean, bigint, symbol, null, undefined.

Destructuring objects in Javascript - ngbind - Angular 4+

Could someone tell me how to use destructured data in ng-bind in angular 4+?
I've come across how to use destructured object/array from here .
const wes = {
first: 'Wes',
last: 'Bos',
links: {
social: {
twitter: 'https://twitter.com/wesbos',
facebook: 'https://facebook.com/wesbos.developer',
},
web: {
blog: 'https://wesbos.com'
}
}
};
Trying to bind the data like below:
let {first : f, last:l} =wes;
In the html I simply used {{f}},
but it doesn't show anything. Did I understand wrongly ?
Please refer to what I did: stackblitz
Thanks all
You cannot directly use the object destructuring in angular, because it needs to be binded to the component directly.
Taking your sample, you can do something like this:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular 4';
count = 5;
_destructuring = '';
ngOnInit() {
const tmp = {a: 'hello'};
const {a: _destructuring} = tmp;
this._destructuring = _destructuring;
}
}
Updated example:
https://stackblitz.com/edit/angular-ngmodel-write-value-er4dcv?file=app/app.component.ts
Alternatively, you might want to use Object.assign on angular component's this. However, this would involve writing far much code than needed, so...
EDIT: as requested, here is the sample code with your original object, and the (working) example: https://stackblitz.com/edit/angular-ngmodel-write-value-lf97lr?file=app/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 {
name = 'Angular 4';
count = 5;
_destructuring = '';
_nested = {};
ngOnInit() {
const tmp = {a: 'hello'};
const {a: _destructuring} = tmp
this._destructuring = _destructuring;
// Original (nested) object
const wes = {
first: 'Wes',
last: 'Bos',
links: {
social: {
twitter: 'https://twitter.com/wesbos',
facebook: 'https://facebook.com/wesbos.developer',
},
web: {
blog: 'https://wesbos.com'
}
}
};
// Object destructuring (links.social.facebook -> fb, links.social.twitter -> tw)
const {
links: {
social: {
facebook: fb,
twitter: tw
}
}
} = wes;
// Assign to the local property, available in the component.
Object.assign(this._nested, {
fb: fb,
tw: tw
});
}
}
Well seems to work great :
const person = {
first: 'John',
last: 'Doe',
};
const { first, last } = person;
const { first: f, last: l } = person;
console.log(first, last);
console.log(f, l);

How to push object into an object array in Angular 6?

I have an empty object array like this groupList:any = {} and now I want to push an object into it. I am trying to name and description as an object.
It is not an array, array is represented like [] , probably you need
groupList:any = [];
and then,
this.groupList.push({name:'you',description:'what is array'});
app.component.ts
declare var require: any;
import { Component } from '#angular/core';
import { OnInit } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
groupList:any = [];
arrayVal:any;
currentVal : any;
title = 'projectchart';
public array = [{"id":1},{"id":3},{"id":5}];
getPrev(){
this.array.forEach((item, index) => {
this.groupList.push(item.id);
});
console.log(this.groupList);
}
}
app.component.html
<button (click) ="getVal()">Previous Value</button>

How to check if two strings are almost equal with Angular

I have a quiz app made with Ionic and Angular 4. User have to submit answer, I check if it's the same as the good answer or not.
I would like to check string correspondence, and handle event according to the correspondence between good answer and user answer.
In Exemple :
If the answer is 'azerty', and he wrote 'mzerty', I would like to allow him to continue.
If user wrote 'qwerty', or something too different, he failes.
A simple demo with Levenstein distance would be like that:
Typescript
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup } from '#angular/forms';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
import levenshtein from 'fast-levenshtein';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
form: FormGroup;
score$: Observable<number>;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.initForm();
this.initScore();
}
private initForm() {
this.form = this.fb.group({
str1: '',
str2: '',
});
}
private initScore() {
this.score$ = this.form
.valueChanges
.pipe(
map(({str1, str2}) => levenshtein.get(str1, str2))
);
}
}
HTML
<form [formGroup]="form">
<input type="text" formControlName="str1">
<br>
<br>
<input type="text" formControlName="str2">
</form>
<br>
<div>
Levenshtein score: {{ score$ | async }}
</div>
Stackblitz live demo: https://stackblitz.com/edit/angular-usydyu
You can simply create a method which will return you how many characters are matched. so on basis of matched characters and the length of string you can decide weather its a good answer or not.
function checkEq(str1, str2){
var arr1 = str1.split('');
var arr2 = str2.split('');
var counter = 0;
for(var i=0;i<arr1.length;i++){
if(arr1[i]==arr2[i]){
counter++;
}
}
return counter;
}

Categories

Resources