Objective: I am trying to build a website URL by concatenating a variety of variables. I get some from JSON file (audience, country, language) + using constants (baseUrl, tailUrl) + some logic applied to an attribute from JSON file (subdir)
Struggle: I have a service that's getting objects from a JSON and then those objects are being used within the app. My original struggle was to map an object from an array to something else (solved using map and switch/case and that worked fine for an array). However, I am having trouble using the map function with these JSON objects.
So in the .html, I am able to loop through the JSON objects just fine, like so:
`
<table class="table table-striped">
<thead>
<tr>
<th>Audience</th>
<th>Country</th>
<th>Language</th>
<th>URL</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let i of siteUrl; let b =index">
<td>{{i.audience}}</td>
<td>{{i.country}}</td>
<td>{{i.language}}</td>
<td>{{(baseUrl)+(i.audience+"/")+(i.country+"/")+(i.language+"/")+(tailUrl)}}</td>
</tr>
</tbody>
</table>
`
However, when I try to do map the objects from the service, I am unable to do so
`
ngOnInit(){
{
this.baseUrl=baseUrlConst;
this.tailUrl=urlTailConst;
this.siteService=smap.map(item =>{
switch (item.audience) {
case 'ABC':
item.audiencesubdir = 'DEF';
break;
case 'UVW':
item.audiencesubdir = 'XYZ';
}
})
}
}
`
I tried arrays instead of JSON and that works fine, but the objects in the JSON itself don't like this function. My understanding of Angular is novice.
Related
Is it possible to convert an html input to JSON using mulesoft?
For my case specifically, I am trying to convert an HTML table to JSON arrays.
Input:
<table>
<tr><td>id</td><td>value1</td><td>value2</td></tr>
<tr><td>0 </td><td>0 </td><td>0 </td></tr>
<tr><td>0 </td><td>1.5 </td><td>2.15 </td></tr>
</table>
Output:
"JsonOutput" :[
{id:"0",value1:"0",value2:"0"},
{id:"1",value1:"1.5",value2:"2.15"}
]
What you can do is fetch the top tr element from the table and use it to determine the headers. Then you can create the JSON dynamically using that headers array.
%dw 2.0
var tableAsArray = payload.table.*tr
var tableHeaderRow = tableAsArray[0].*td
var tableValuesRow = tableAsArray[1 to -1]
output application/json
---
{
"JsonOutput": tableValuesRow map ((tr) -> {
(tr.*td map ((td, index) -> {
(tableHeaderRow[index]): td
}))
})
}
I am new to angular. I am trying render some dynamic template strings that are coming from a server in a component.
The component looks like this -
<div [innerHTML]='templateString'></div>
In component.ts file, we have
obj = {
prop: 'text to display'
}
templateString = '<p class="text-primary">{{obj.prop}}</p>' // this is dynamic, e.g. received from an http request
If we leave it like this, it will render as '{{obj.prop}}' whereas I want it to show is 'text to display'. Currently I have written a script that takes the templateString and obj and returns the properties by using .split('{{') etc. Is there some simpler built-in way to do this in angular? I.e. compiling the template strings dynamically onChanges or onInit, so that I can take advantage of ngFor to display values inside an array property for instance.
arr = [
{prop: 'text1'},
{prop: 'text2'}
]
templateString = '<p *ngFor="let item of arr">{{item.prop}}</p>'
Currently I am using a custom syntax [[arr::{{this.prop}}]] which my script can read and iterate over arrays, but it is pretty unreliable and non standard.
I have seen this Angular: bind variables inside [innerHtml], but it seems overqualified since I do not need to put other components inside the template string. Just standard html, with some directives like ngFor, ngIf etc,
I think you can just use inline concatenation
`this is the string ${this.foo} more string here`
No rocket science needed. This will work for you!
templateString = '<p class="text-primary">'+ this.obj.prop + '</p>' ;
Below is my method from .ts file. With this method the keys are displayed but I am unable to fetch the nested JSON data.
generateArr(obj) {
return Object.keys(obj).map((key) => {
console.log(key, obj[key]);
return {key: key, value: obj[key]};
});
}
Below is my HTML code.
<li *ngFor="let ob of books">
<p *ngFor="let objArrEle of generateArr(ob);let i=index">
{{objArrEle.key}}: {{objArrEle.value}}
</p>
</li>
Please tell me the solution.
If you are trying to fetch the nested JSON using interpolation {{}} in HTML, it will display[Object object]. If you want to display the nested data also, you may want to recursively call generateArr(obj) for each nested property. If you are using Angular 7, have a look at KeyValuePipe.
Created a solution for you using stackblitz https://stackblitz.com/edit/angular-nestedjson. you can nest JSON for any level. I'm not so good with CSS, please fell free to change that.
I'm getting a json using $http.$get, but to it be "compatible" with Angular, I'm having to convert it this way:
$http.get('/api/v1.0/plans').
success(function(data) {
var plans = [];
for(var propertyName in data)
{
if (data.hasOwnProperty(propertyName))
{
plans.push(data[propertyName]);
}
}
$scope.plans = angular.fromJson(data);
});
But, of course, I think this would be the way to go in this case, as shown in docs:
$http.get('/api/v1.0/plans').
success(function(data) {
$scope.plans = data;
});
I can see the difference between the objects, I just don't know how to fix it:
data (not accepted by angular)
Object {alfa: Object, beta: Object, delta: Object, omega: Object}
plans (converted and accepted by angular)
[Object, Object, Object, Object]
Could you, please, tell what I'm doing wrong?
You need to elaborate a bit more about what kind of "compatible" problem you refered to in your first sentence. As far as I know, both JSON representations work just fine in Angular for me.
I believe the question here boils down to how the data will be used after being set to $scope.plans. If you are trying to use ng-repeat with $scope.plans afterward, then how you iterate will differ slightly depending whether the data you receive is a JSON object or JSON array.
For JSON object, you use
<tr ng-repeat="(name, plan) in plans">
<td> {{name}} </td> <td> {{ plan | json }} </td>
</tr>
For JSON array, you use
<tr ng-repeat="plan in plans">
<td> {{$index}} </td> <td> {{ plan | json }} </td>
</tr>
Of course, for plan specified in HTML snippets above, you can access object inner fields with dot notation as usual (i.e., {{plan.title}}, {{plan.description}}, etc.). {{plan | json}} just converts JSON object into string so you can see object content directly in HTML.
For details on how to use ngRepeat, you can read more at https://docs.angularjs.org/api/ng/directive/ngRepeat
In case a (Object {alfa: Object, beta: Object, delta: Object, omega: Object} your api return object so you have to define plans as a object not array that should works
$scope.plans = {}; // <-object
$http.get('/api/v1.0/plans').
success(function(data) {
angular.copy(data, $scope.plans);
});
in case you api will return array of object you have to define plans as a array ie:
$scope.plans = []; // <-array
$http.get('/api/v1.0/plans').
success(function(data) {
angular.copy(data, $scope.plans);
});
Please see bin here
I am getting json from asana that is an object (data) of several objects. How do I make data an array?
{"data":{"id":5571422294129,"created_at":"2013-05-24T15:31:50.340Z","modified_at":"2013-05-24T15:32:21.260Z","name":"testProject","notes":"","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}}
I am trying to put this in a data table using aoColumns. If there is no need to convert "data" to an array please let me know how to use this JSON in datatables without it.
It is not that complicated. You can use DataTables aaData for this. I assume your JSON contains multiple "data":{..}, "data":{..}, "data":{..} ?
Then, consider this as test data :
var data = [
{"data":{"id":1571422294129,"created_at":"2010-05-24T15:31:50.340Z","modified_at":"2010-05-24T15:32:21.260Z","name":"testProject","notes":"","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}},
{"data":{"id":2571422294129,"created_at":"2011-05-24T15:31:50.340Z","modified_at":"2011-05-24T15:32:21.260Z","name":"Project A","notes":"","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}},
{"data":{"id":3571422294129,"created_at":"2012-05-24T15:31:50.340Z","modified_at":"2012-05-24T15:32:21.260Z","name":"Project B","notes":"bla bla","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}}
];
HTML markup
<table id="test">
<thead>
<tr>
<th>archived</th>
<th>created_at</th>
<th>id</th>
<th>modified_at</th>
<th>name</th>
<th>notes</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
convert JSON to aaData-array :
var aaData = [];
for (var i=0;i<data.length;i++) {
aaData.push([
data[i].data.archived,
data[i].data.created_at,
data[i].data.id,
data[i].data.modified_at,
data[i].data.name,
data[i].data.notes
]);
}
Initialize the table
$('#test').dataTable({
"aaData": aaData
});
result :
I am not sure what you are exactly attempting to do, but...
If you are trying to deserialize the JSON into a data table you want something like this. This will take your JSON and deserialize it to an object, it won't exactly work with a data table but rather custom classes decorated with DataContract and DataMember attributes. But I think it may be a good starting point for you.
Public static T DeSerialize<T>(string strJSON)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(strJSON));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
ms.Dispose();
return (obj);
}
Here is a very useful article regarding serializing JSON. HTH :)
http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx
Regards