I'm trying to use iteration helper inside another one. But the inner helper doesn't output anything.
That's the handlebars template :
{{#people}}
<h4>{{firstName}} {{lastName}}</h4>
{{#students}}
<h3>{{firstName}} {{lastName}}</h3>
{{/students}}
{{/people}}
And that is my JSON :
{
people : [
{ firstName: "Yehuda", lastName: "Katz" },
{ firstName: "Carl", lastName: "Lerche" },
{ firstName: "Alan", lastName: "Johnson" }
],
students: [
{ firstName: "Mike", lastName: "Smith" },
{ firstName: "Dan", lastName: "Knight" },
{ firstName: "Griffin", lastName: "Smith" }
]
}
Whats the solution for this problem?
Try the code online and fast here : http://tryhandlebarsjs.com/
The expression {{#people}}...{{/people}} gives rise to three contexts:
{ firstName: "Yehuda", lastName: "Katz" },
{ firstName: "Carl", lastName: "Lerche" },
{ firstName: "Alan", lastName: "Johnson" }
so there are no students in any of those contexts, which is why the inner expression {{#students}}...{{/students}} gives no output.
Can you elaborate on what it is you are trying to achieve?
Thanks Very much J P....your answer is great...
The right code is :
{
people : [
{ firstName: "Yehuda", lastName: "Katz", students: [{ firstName1: "Mike", lastName1: "Smith"
}] },
{ firstName: "Carl", lastName: "Lerche", students: [{ firstName1: "Mike", lastName1: "Smith"
}] },
{ firstName: "Alan", lastName: "Johnson", students: [{ firstName1: "Mike", lastName1: "Smith"
}] }
],
}
Related
Here is my json file
{
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": m,
"data": { "age": 26, "born": "UK" }
},
]
}
This data array could have more entries.
I have to map the values into an interface which looks like:
InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
I am unable to change the interface. So I'm trying to do some pseudo coding.
const list;
list = convertToInterfacePerson = (value): Array<InterfacePerson> => {
return {
id: value.id,
title: if(value.gender === "m")? "Mr" : "Mrs",
firstName: value.firstName,
lastName: value.lastName,
age: value.data.age,
//...
}
}
I think you were trying to use a conversion mapping function called convertToInterfacePerson but you hadn't set it up yet (separately from trying to use it). The code below shows it declared and used within a map Array method call. I believe this resolves the error(s) you were getting.
// Copied in the JSON for demonstration
const sourceJson = {
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": "m",
"data": { "age": 26, "born": "UK" }
},
]
};
// Declared the InterfacePerson interface
interface InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
// Declared the conversion mapping function (optional parameter typing included)
const convertToInterfacePerson = (value: { firstName: string, lastName: string, type: string, id: string, gender: string, data: { age: number, born: string } }): InterfacePerson => {
return {
id: value.id,
// Removed the `if` statement due to ternary conditional
title: ((value.gender === "m") ? "Mr" : "Mrs"),
firstName: value.firstName,
lastName: value.lastName,
// Wrapped the value.data.age in a string conversion
age: String(value.data.age),
location: value.data.born
};
}
// Declared and assigned the list based on the returned array from the mapping function (each element is applied in the `convertToInterfacePerson` function)
const list = sourceJson.data.map(convertToInterfacePerson);
// Show the result of the conversion
console.log(JSON.stringify(list, null, 2));
And for a live example, check out this TypeScript Playground script containing this solution.
I am receiving a json response in an Angular 11 app and I have created an interface corresponding to that json object. The json object is
{
"division": {
"uid": "f5a10d90-60d6-4937-b917-1d809bd180b4",
"name": "Sales Division",
"title": "Sales",
"type": "Form",
"formFields": [
{
"id": 1,
"name": "firstName",
"label": "First Name",
"value": "John"
},
{
"id": 2,
"name": "lastName",
"label": "Last Name",
"value": "Smith"
}
]
}
}
The typescript interface I created for this json object is
export interface FormField {
id: number;
name: string;
label: string;
value: string;
}
export interface Division {
uid: string;
name: string;
title: string;
type: string;
formFields: FormField[];
}
export interface Division {
division: Division;
}
I am using a service division.sevice.ts to fetch the above json response from API and everything works fine. I am trying to write unit tests for the this service in the division.service.spec.ts file. I created a mockDivisionObj inside this file for testing purpose which is shown below.
mockDivisionObj = {
"division": {
"uid": "f5a10d90-60d6-4937-b917-1d809bd180b4",
"name": "Sales Division",
"title": "Sales",
"type": "Form",
"formFields": [
{
"id": 1,
"name": "firstName",
"label": "First Name",
"value": "John"
},
{
"id": 2,
"name": "lastName",
"label": "Last Name",
"value": "Smith"
}
]
}
}
An error is shown which says
Property 'division' is missing in type '{ uid: string; name: string; title: string; type:
string; formFields: { id: number; name: string; label: string; value: string; }[]; }' but
required in type 'Division'.
I think the way I created the interface may be wrong but I couldn't figure out what exactly is causing the issue. Please help me out with this.
I was able to fix the issue by changing the name of one of the interfaces in the file to 'AppDivision' as shown below.
export interface FormField {
id: number;
name: string;
label: string;
value: string;
}
export interface Division {
uid: string;
name: string;
title: string;
type: string;
formFields: FormField[];
}
export interface AppDivision {
division: Division;
}
The same name for two interfaces caused the error in the unit test mock object.
Your code is fine.To solve this error you can try the code below =>
this.division = this.mockDivisionObj.division as Division;
Check the Link: StackBlitz Demo link.
i want to create a pipe in Angular 9 that translate my table words in various language.
I have created a JSON file that contains a key and the value for a translation service. I have also created some interfaces for this json file.
translate.json
{
"lang":[
{
"IT": [
{ "name": "Nome" },
{ "surname": "Cognome" },
{ "email": "E-mail" },
{ "cf": "Codice fiscale" },
{ "phone": "Cellulare" },
{ "age": "Età" },
{ "city": "Città" },
{ "job": "Lavoro" }
]
},
{
"EN": [
{ "name": "first name" },
{ "surname": "last name" },
{ "email": "E-mail" },
{ "cf": "Fiscal code" },
{ "phone": "Phone" },
{ "age": "Age" },
{ "city": "City" },
{ "job": "Job" }
]
}
]
}
translateInterface.ts
export interface Lang {
lang: (Langs)[];
}
export interface Langs {
IT: (ITEntityOrENEntity)[];
EN: (ITEntityOrENEntity)[];
}
export interface ITEntityOrENEntity {
name: string;
surname: string;
email: string;
cf: string;
phone: string;
age: string;
city: string;
job: string;
}
translate.service.ts
translate(key: string, lang:string) {
return this.http.get<Langs>('assets/json/translate.json').subscribe((res: Lang) => console.log(res))
}
I have updated the json and the interface, now how i can return one object of the IT array?
I see multiple issues.
You don't need to define the properties IT and EN as arrays in the JSON file. It could very well be plain JS objects.
{
"IT": {
"name": "Nome",
"surname": "Cognome",
"email": "E-mail",
"cf": "Codice fiscale",
"phone": "Cellulare",
"age": "Età",
"city": "Città",
"job": "Lavoro"
},
"EN": {
"name": "first name",
"surname": "last name",
"email": "E-mail",
"cf": "Fiscal code",
"phone": "Phone",
"age": "Age",
"city": "City",
"job": "Job"
}
}
There is no need for two different interfaces. You could assign one single interface.
export interface Details {
name: string;
surname: string;
email: string;
cf: string;
phone: string;
age: string;
city: string;
job: string;
}
You are defining the type as array in Langs interface instead of the defined details interface. You could do something like
export interface Langs {
IT: Details;
EN: Details;
}
At the moment you're wrongfully returning the subscription instead of the observable from the function. You could return the observable from the service and subscribe to it the component controller.
Service
translate(language: string): Observable<Details> {
return this.http.get<Langs>('assets/json/translate.json').pipe(
map(response => response[language])
);
}
Component
ngOnInit() {
this.translateService.translate('IT').subscribe(
details => { this.details = details },
error => { }
);
}
Template
<span>{{ details?.name }}</span>
<span>{{ details?.surname }}</span>
<span>{{ details?.email }}</span>
...
Working example: Stackblitz
I'm trying to create an REST API in JSON. I have 2 models, an business and an address. An Address is part of a business
When I try to create a POST request with the following JSON
{
"name" :"GRIT",
"adress":
{
"street" : "test",
"number": "5",
"city":"leuven",
"postalcode":"2900",
"country":"BEL"
}
}
I get the following error
{
"error": {
"errors": {
"adress": {
"message": "Cast to ObjectID failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\" at path \"adress\"",
"name": "CastError",
"stringValue": "\"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\"",
"kind": "ObjectID",
"value": {
"id": "5ad8b5e4ac4b1a443877bfc2",
"street": "test",
"number": "5",
"city": "leuven",
"postalcode": "2900",
"country": "BEL"
},
"path": "adress",
"reason": {
"message": "Cast to ObjectId failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\" at path \"adress\"",
"name": "CastError",
"stringValue": "\"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\"",
"kind": "ObjectId",
"value": {
"id": "5ad8b5e4ac4b1a443877bfc2",
"street": "test",
"number": "5",
"city": "leuven",
"postalcode": "2900",
"country": "BEL"
},
"path": "adress"
}
}
},
"_message": "Business validation failed",
"message": "Business validation failed: adress: Cast to ObjectID failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\" at path \"adress\"",
"name": "ValidationError"
}
}
These are my mongoose models
const mongoose = require('mongoose');
const businessSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name:{
type: String,
required: true,
},
adress:{
type: mongoose.Schema.Types.ObjectId,
ref: 'Adress',
required:true
}
});
module.exports = mongoose.model('Business', businessSchema);
const mongoose = require('mongoose');
const adressSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
street:{
type: String,
required: true
},
number:{
type: int,
required: true
},
city:{
type: String,
required: true
},
postalCode:{
type: String,
required: true
},
country:{
type: String,
required: true
}
});
module.exports = mongoose.model('Adress', adressSchema);
The following is my Post request
//POST -> Register a business
router.post('/',function(req,res){
const business = new Business({
id: new mongoose.Types.ObjectId(),
name: req.body.name,
adress:{
id:new mongoose.Types.ObjectId(),
street: req.body.adress.street,
number: req.body.adress.number,
city: req.body.adress.city,
postalcode: req.body.adress.postalcode,
country:req.body.adress.country
}
});
business
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Business created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
module.exports = router;
What did I do wrong? Does the adress doesn't save or do I link the two models wrong with eachother
I am using MongoDB as a Datbase
Take a look at the mongoose docs.
You are trying to set a ObjectId property with an Adress object. What you have to do is first save your adress object, and then reference it inside your business object.
PS: You should name your ids as _id since thats the convention used in MongoDB.
It would look something like this:
let adress = new Adress({
_id: new mongoose.Types.ObjectId(),
street: req.body.adress.street,
number: req.body.adress.number,
city: req.body.adress.city,
postalcode: req.body.adress.postalcode,
country: req.body.adress.country
});
adress
.save()
.then(() => {
let business = new Business({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
adress: adress._id
});
business
.save()
.then((result) => {
console.log(result);
res.status(201).json({
message: "Business created"
});
});
});
I have a C# List which looks like this:
var reqUsers = from user in users
select new
{
username = user.username,
firstName = user.firstName,
lastName = user.lastName,
email = user.email
};
I use the below to convert / serialize to JSON ( Newtonsoft.JSON ):
var json = JsonConvert.SerializeObject(reqUsers);
With the above code I get a json string like this:
[{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan#test.com" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "al#test.com" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan#test.com" } ]
however here is what I need to get : since I am using handlebars templating -
var testdata = {
users: [
{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan#test.com" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "al#test.com" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan#test.com" } ]
How can use the Serializer to name the JSON array as above ?
Use:
var json = JsonConvert.SerializeObject(new { users = reqUsers });
use:
var json= new JavaScriptSerializer().Serialize(reqUsers);