String Interpolation Resulting in Undefined Error in Angular 2 App - javascript

I am trying to display some data to the view in my Angular 2 app via string interpolation. For most of the page that's working, but I'm getting an error in this one section that's not making sense to me. It looks like it should work, but I'm getting an 'undefined' error.
Here's what the data looks like that I'm accessing (note: "contacts" is on the root of the document):
"contacts": [
{
"contact": {
"_id": "111111111",
"email": [
"person#email.com"
],
"name": {
"first": "Person",
"last": "Lastname"
}
}
]
I am trying to access the email value in my template using this:
First I tried accessing the email address like this:
{{contacts[0]?.contact?.email[0]}}
But got this error:
Cannot read property '0' of undefined
So then I tried a named index:
{{contacts['contact']?.email[0]}}
This is also not working. I get this error:
Cannot read property 'contact' of undefined
And this is for a record where I know there is a value there. So I'm unclear why this isn't working? Anything look wrong about how I'm accessing the values here?

Contacts is an array, you should access with index
{{contacts[0]?.contact?.email[0]}}
if not use ngFor
<li *ngFor="let conctact of contacts">
{{ conctact.email[0]}}
</li>

Related

convert mongodb object to javascript object

I pass a config file to another node.js module when starting it. The config file contain the following json:
"resolution": {
"activated": true,
"types": [
{"of": 23}
]
}
When I print the received types array in the called node.js module, it looks like
console.log('types array: '+ this.config.resolution.types)
//output
types array: [object Object]
if I tried to print the text by using JSON.stringify(), I get the following result
[{"of":23}]
My problem start when I try to replace the types array with a list retried from a mongodb database. my code looks like:
"resolution": {
"activated": true,
"types": [
savedTypes
]
}
Now when I print the received types config, it looks like this:
types array: { _id: 5ab9fe8fd1f64303cd98f122, of: 23, __v: 0 }
and the called node module is not working properly with this config. How can I cast this to an object? I tried to use
JSON.parse(savedTypes)
and get the error
SyntaxError: Unexpected token _ in JSON at position 2
If you use mongoose, I think that the correct form is using ToJSON() function.
Otherwise, you can use JSON.parse(JSON.stringify(data)); But I think that de first form is better.
=)
Alternatively you could use .toObject() method from javascript to convert mongoose object into javascript object.
Here is a reference link to dig out more
https://alexanderzeitler.com/articles/mongoose-tojson-toobject-transform-with-subdocuments/

node.js correct extending of json objects

I'm currently using node-ews in a project to access an Exchange Web Server via node.js. Now i ran into a weird problem. To run for example a "CreateItem" request, which can be an E-Mail or Appointment for example, I'm giving the function the arguments as a json similar to this
var args = {
"attributes" : {
"SendMeetingInvitations" : "SendToAllAndSaveCopy"
},
"SavedItemFolderId": {
"DistinguishedFolderId": {
"attributes": {
"Id": "calendar"
}
}
},
"Items" : {
"CalendarItem" : {
"Subject" : "",
"Body" : {
"attributes" : {
},
"$value" : ""
},
"ReminderIsSet" : "true",
"ReminderMinutesBeforeStart" : "30",
"Start" : "",
"End" : "",
"IsAllDayEvent" : "false",
"LegacyFreeBusyStatus" : "Busy",
"Location" : ""
}
}
};
As the REST-API I'm writing will receive Attributes like Subject, Start, End etc. I initially stripped out those out of the JSON and would define them later like
args.Items.CalendarItem.Subject = req.body.Subject;
Oddly this will make the internal validation of node-ews fail and tell me that CalendarItem has an invalid Child Subject. If i leave Subject als an empty string in the initial args and later change it set it to req.body.Subject it works just fine.
My question is this: Is the Object somewhat different if I later add attributes and if yes is there a way to do it right? Because I don't think its the best way to have a bunch of empty Attributes in my Object if they aren't used and define standard values for all of them even if api won't require them to be sent.
Would great if someone knew the answer. Hope i could clarify what the problem is
Ok,
so the problem seems to be this. Internally the JSON "object" seems to have an order based on the order the variable is defined. in JavaScript this is no problem. But when the xml is parsed, the tag that was defined last will also be at the end of the xml so if you had
<someTag>
<variable2 />
<variable3 />
</someTag>
and you add variable1 to your json by someTag.variable1 = x in the end the xml will look like this after beeing parsed by node-ews
<someTag>
<variable2 />
<variable3 />
<variable1 >x</variable1>
</someTag>
Now unfortunately the exchange web server seems to be picky about the order of the xml tags. so when you build your json be sure to use the direct order. Changing content of the json later will not affect the order.

HTML is not recognizing a defined variable in a <script> tag [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
I sent a GET request with javascript and parsed the result
var result = JSON.parse(response);
then defined the variable "title"
var title = result.title;
Next I tried to load the variable into a tag with the id="fishplanet-title"
but HTML gave an error saying "title" wasnt defined.
document.getElementById("fishplanet-title").innerHTML = title;
I know the request is going through because I have it logging to console.
Heres the request:
https://hastebin.com/eloqojimit.js
Heres the response:
https://hastebin.com/vinadafelo.json
Heres the errors:
Uncaught ReferenceError: title is not defined
at user.html:178
result.title will not work. The title property is within an array so you need to iterate over it to get the title value:
{
"appnews": {
"appid": 380600,
"newsitems": [
{
"gid": "2175660043472720797",
"title": "QuestionsAnswers",
"url": "http://store.steampowered.com/news/externalpost/steam_community_announcements/2175660043472720797",
"is_external_url": true,
"author": "Olcha",
"contents": "1.\"What is the garage icon for at the bottom of the Inventory page? Will this be for boat access and when can we expect boats to be launched?\" That’s right - the Garage will soon be the place from where you can access Boats. That’s exactly what we are currently working hard on and we plan to release this feature in the nearest future. Actually, we’ll share a video with you guys next week! Make sure to keep track of our news - it’ll be fun! 2. \"Will we see traditional carp fishing features such a...",
"feedlabel": "Community Announcements",
"date": 1506799022,
"feedname": "steam_community_announcements",
"feed_type": 1,
"appid": 380600
}
]
,
"count": 277
}
}
To get to the title property, you'll need to do something like this:
var title = JSON.parse(result).appnews.newsitems[0].title;
Since newsitems is an array, you will need to do some iterating if that ever returns more than one.

Angularjs: 'SyntaxError: Unexpected token , ' when loading object

I'm trying to use Symphony CMS to output its XSL as JSON, for use in the angular phonecat app example from the tutorial. My list view json is output as an array with [{ }] brackets around it. My detail view json is output with only { } around it:
{
"position": 1,
"order": 3,
"total": "1",
"id": "sunt",
"sym_id": "21",
"cat": "back-end",
"imageUrl": "http://localhost:8080/workspace/images/phones/Nondell-streak-7.0.jpg",
"name": "Sunt",
"done": "No",
"priority": "medium",
"date-created" : "18 November 2015",
"date-modified" : "19/11/15 10:41am",
"date-due" : "18/11/15 2:13pm",
"snippet": "Quam nihil molestiae"
}
When loading my page the list view loads. When I click on an item the detail view tries to load but I get: SyntaxError: Unexpected token ,. Why? The syntax seems normal to me?
A big problem I am struggling with is that my json is created dynamically with the CMS but no actual files are on the server as far as I know.
Before I was getting the error: Error in resource configuration for action get. Expected response to contain an object but got an array so I made some changes so the list is output as an array, and the single views are output as an object.
My json is generated on localhost:8080/json/{parameter}. The param is 'todos' when not set. So my list view is situated at localhost:8080/json/todos. The param takes the selected object's name, so my detail view would be at localhost:8080/json/foo when I press the link generated by angular.
I hope my question is complete and makes sense :D

How to access data within json using nodejs

I'm trying to access data within a json file using nodeJS
When I run this I get the error : TypeError: Cannot read property 'postcode' of undefined. Any Suggestions?
{
"apiName": "Restaurants",
"pages": [
{
"pageUrl": "https://url",
"results": [
{
"address": "3F Belvedere Road Coutry Hall, London, SE17GQ",
"phone": "+442076339309",
"name": "Troia",
"postcode": "SE17GQ"
}
]
}
]
}
var myData = require('./jsonFile.json');
console.log(myData.pages.result.postcode);
Try to access data as below:
console.log(myData.pages[0].results[0].postcode);
The value in the bracket is the index of element to access.
Its the common singular/plural trap, I fall for it all the time.
In your json, pages & results are arrays. You need to access these with an index. Also, you have a typo in the name.
Try this:
console.log(myData.pages[0].results[0].postcode);
This will gave you correct answer.
console.log(myData.pages[0].results[0].postcode);

Categories