Iteration of Object of arrays of objects Angular4 - html

I need to iterate Object of array of objects in anchor tag. Following is the format of my code
{"1":{"uri":"test1","name":"test1","icon":"http:\/\/dummyurl\/images\/icons\/test1-icon.png","application_id":1},"2":{"uri":"test2","name":"test2","icon":"http:\/\/dummyurl\/images\/icons\/test2-icon.png","application_id":2},"3":{"uri":"test3","name":"test3","icon":"http:\/\/dummyurl\/images\/icons\/test3-icon.png","application_id":3},"4":{"uri":"test4","name":"test4","icon":"http:\/\/dummyurl\/images\/icons\/test4-icon.gif","application_id":4},"5":{"uri":"test5","name":"test5","icon":"http:\/\/dummyurl\/images\/icons\/test5-icon.png","application_id":5}}
.ts file
this.applicationService.getApplication(id)
.subscribe(applications => {
this.applications = applications.response;});
html
<a class="dropdown-item" href="#" NgForOf=" let obj of applications">
{{obj.name}} </a>
I am stuck in this from last 3-4 hours. Any help will be appreciated.

You can loop through them using Object.keys(apps)
this.applicationService.getApplication(id)
.map(result => result.response)
.subscribe(apps=> {
this.applications = Object.keys(apps).map(k => apps[k])
});
HTML
<div *ngFor="let app of applications">{{app | json}}</div>

Related

ReactJs App's mapped list of buttons from Json file only have the last value of json array

I am making list of button that will lead to different YouTube videos on ReactJs page. The issue is that when I map the links from json file (which contains video links), all the buttons get the last link of the mapped array. I need a way that all the rendered buttons will get their respective links. My code is below, I am using react ModalVideo to show my YouTube video.
<ul className="list-unstyled">
{datalist.lectures.map((value, index) => {
return (
<li key={index}>
<ModalVideo channel='youtube' autoplay isOpen={isOpen} videoId={value} onClose={() => setOpen(false)} />
<button className="play-icon" onClick={()=> setOpen(true)}> <i className="las la-play"></i> Lecture: {index+1}</button>
</li>
)})}
</ul>
All the links are coming from Json file where the code looks like this
"lectures": [
"BT4YihNXiYw",
"NSFLhnv2pQI",
"sEPxqpFZit8",
"fU8QhoUJ_sE",
"r3XFYOtvUng",
"MZAkMddxhpg"
]
I think the problem I have right now is that after the page render and mapping ends it only remembers what the last link is store in value, because of that no matter which button i click it shows me the last value of the mapped array
Just some quick ideas looking at the minimal snippets available.
let's not to render multiple ModalVideo component like above, move it out from the map.
Use another state to keep track the change of the youtube videos' ID.
For example
const [isOpen, setOpen] = useState(false);
const [videoId, setVideoId] = useState(null);
const playVideo = (vid) => {
setOpen(true);
setVideoId(vid);
};
return (
<div>
<ModalVideo
channel='youtube'
autoplay
isOpen={isOpen}
videoId={videoId}
onClose={() => setOpen(false)}
/>
<ul className="list-unstyled">
{
datalist.lectures.map((value, index) => {
return (
<li key={index}>
<button className="play-icon" onClick={() => playVideo(value)}>
<i className="las la-play"></i>
Lecture: {index + 1}
</button>
</li>
)
})
}
</ul>
</div>
);

JSON data undefined while using in HTML

I am new to Angular and Node and have been working on a full stack development. I am reading the data on Angular from Node which I have connected to MySQL. I am somehow stuck at outputting my data on an HTML page. I am getting the error of undefined when I try to access my data in my HTML.
This is the JSON data that I have read on my console
This is my typescript code that converts JSON object to string:
private onFetchPosts()
{
this.http
.get<{[key: string]: DataBase}>('http://localhost:3000/show') //Here, DataBase is an interface
.pipe(map(responseData => {
const postsArray: DataBase[] = [];
for (const key in responseData){
if(responseData.hasOwnProperty(key)){
postsArray.push({...responseData[key], idoffice: key});
}
}
return postsArray;
}))
.subscribe(posts => {
this.dbData = posts;
console.log(this.dbData);
});
}
When I try to access this data in my HTML code:
<h3>test print</h3>
<li class="list-group-item" *ngFor = "let db of dbData"></li>
<p>{{ db.ActivityType }}</p>
Then, I get this error:
ERROR TypeError: Cannot read property 'ActivityType' of undefined
Can you please help me out?
use db.ActivityType inside li .
<li class="list-group-item" *ngFor = "let db of dbData">
<p>{{ db.ActivityType }}</p>
</li>
<h3>test print</h3>
<li class="list-group-item" *ngFor = "let db of dbData">
<p>{{ db.ActivityType }}</p>
</li>
li tag closed wrongly.

when using a GET method data is coming in console not in HTML

I have written my get method inside ngOnInIt(). When I am printing data in console it is visible, but when printing in HTML using interpolation, it is returning [ object object]
{{filteredCourses}} ==> [object object]
and when i am using {{course.category|json}} so here i am getting all values of array ["course" : "database" , "category" : "database" , "length" : "2hr" ] thats how the value is coming
html :-
<div class="courses" fxLayout="row wrap" fxLayoutAlign="center" [#animateStagger]="{value:'50'}">
<div class="course" *ngFor="let course of filteredCourses" fxFlex="100" fxFlex.gt-xs="50"
fxFlex.gt-sm="33" [ngClass]="course.category" [#animate]="{value:'*',params:{y:'100%'}}">
<div class="course-content" fxLayout="column" fxFlex="1 1 auto">
<div class="header" fxLayout="row" fxLayoutAlign="center center"
[ngClass]="course.category + '-bg'">
<div class="category" fxFlex>
{{course.category|json}}
</div>
</div>
</div>
Code:
filteredCourses: any[];
this.product_name = getProduct()['name'];
console.log(this.product_name);
this.token = getToken();
this.httpHeaders = new HttpHeaders({ "Authorization": "Bearer " + this.token });
this._httpClient.get('http://127.0.0.1:8000/api/products/info/'+this.product_name+'/',{headers: this.httpHeaders})
.subscribe(
data => {
this.product = data;
this.courses = data['cources'];
this.filteredCourses = this.courses;
console.log(this.filteredCourses);
},
error => {
console.log(error);
}
);
try using JSON.stringify(yourObject) or maybe in certain cases you can use Object.keys().
You need to use loop if its an array of object or you might want to print the properties of object individually.
But if you want to see the object filteredCourses in template, use json pipe.
{{filteredCourses | json}}
In case you need help to print values using *ngFor or properties, do let us know.
I suppose filteredCourses collection contains an array of objects. So you need to iterate through filteredCourses using ngFor directive to render data in the HTML template.
Like:
<ul>
<li ngFor="let item of filteredCourses">{{item.courseName}}</li>
</ul>

Get selected item from Angular List

I have a list of elements displayed on my HTML page. For whatever element selected, I wish to retrieve the corresponding data from the firebase database.
Here's the code of how I am displaying the list on the HTML page. These items are retrieved from firebase.
<div class="list-group " *ngFor="let year of years | async">
<a routerLink="records" routerLinkActive="active">
<mdb-icon fas icon="table" class="mr-3"></mdb-icon>{{year.key}}</a>
</div>
routerLink="records" , Records.html is where I would like to display the corresponding data.
Records is a html page where...based on the selected "year" , the data should be dynamically loaded.
I would use two services
one for your http calls (apiService) and one for storing the datas in your app (in that case dataService)
in your actual ts
years:any[] = []
//you can trigger that with ngOnInit or other events
this.apiService.getYears.subscribe(
data => {
this.dataService.setYears(data)
this.years = this.dataService.getYears();
}
)
in your html (no more async just data)
<div class="list-group " *ngFor="let year of years | async">
<a [routerLink]="['records/'+ year.key]" routerLinkActive="active">
<mdb-icon fas icon="table" class="mr-3"></mdb-icon>{{year.key}}</a>
</div>
then in your record component
year:any = undefined
//check for ActivatedRoute.params for retrieving the key (here `yearKey`) in your url
ngOnInit(){
if (!(this.year = this.dataService.getYear(yearKey)))
this.apiService.getYear(yearKey).subscribe(
data => this.year = data
)
}
REFERENCES
Services

Angularjs convert string to object inside ng-repeat

i've got a string saved in my db
{"first_name":"Alex","last_name":"Hoffman"}
I'm loading it as part of object into scope and then go through it with ng-repeat. The other values in scope are just strings
{"id":"38","fullname":"{\"first_name\":\"Alex\",\"last_name\":\"Hoffman\"}","email":"alex#mail","photo":"img.png"}
But I want to use ng-repeat inside ng-repeat to get first and last name separate
<div ng-repeat="customer in customers">
<div class="user-info" ng-repeat="name in customer.fullname">
{{ name.first_name }} {{ name.last_name }}
</div>
</div>
And I get nothing. I think, the problem ist, that full name value is a string. Is it possible to convert it to object?
First off... I have no idea why that portion would be stored as a string... but I'm here to save you.
When you first get the data (I'm assuming via $http.get request)... before you store it to $scope.customers... let's do this:
$http.get("Whereever/You/Get/Data.php").success(function(response){
//This is where you will run your for loop
for (var i = 0, len = response.length; i < len; i++){
response[i].fullname = JSON.parse(response[i].fullname)
//This will convert the strings into objects before Ng-Repeat Runs
//Now we will set customers = to response
$scope.customers = response
}
})
Now NG-Repeat was designed to loop through arrays and not objects so your nested NG-Repeat is not necessary... your html should look like this:
<div ng-repeat="customer in customers">
<div class="user-info">
{{ customer.fullname.first_name }} {{ customer.fullname.last_name }}
</div>
This should fix your issue :)
You'd have to convert the string value to an object (why it's a string, no idea)
.fullname = JSON.parse(data.fullname); //replace data.fullname with actual object
Then use the object ngRepeat syntax ((k, v) in obj):
<div class="user-info" ng-repeat="(nameType, name) in customer.fullname">
{{nameType}} : {{name}}
</div>
My advise is to use a filter like:
<div class="user-info"... ng-bind="customer | customerName">...
The filter would look like:
angular.module('myModule').filter('customerName', [function () {
'use strict';
return function (customer) {
// JSON.parse, compute name, foreach strings and return the final string
};
}
]);
I had same problem, but i solve this stuff through custom filter...
JSON :
.........
"FARE_CLASS": "[{\"TYPE\":\"Economy\",\"CL\":\"S \"},{\"TYPE\":\"Economy\",\"CL\":\"X \"}]",
.........
UI:
<div class="col-sm-4" ng-repeat="cls in f.FARE_CLASS | s2o">
<label>
<input type="radio" ng-click="selectedClass(cls.CL)" name="group-class" value={{cls.CL}}/><div>{{cls.CL}}</div>
</label>
</div>
CUSTOM FILTER::
app.filter("s2o",function () {
return function (cls) {
var j = JSON.parse(cls);
//console.log(j);
return j;
}
});