JSON data undefined while using in HTML - mysql

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.

Related

Property 'name' does not exist on type 'string' ngFor in Angular

I got this error while trying to display an array of objects
Error: src/app/components/timeline/timeline.component.html:9:29 - error TS2339: Property 'name' does not exist on type 'string'.
<h4>{{publication.user.name}}</h4>
~~~~
src/app/components/timeline/timeline.component.ts:10:15
10 templateUrl: './timeline.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component TimelineComponent.
in my timeline.component.html I have this:
<div id="publications">
<div *ngFor = "let publication of publications" class="item-publication">
<div class="panel panel-default">
<div class="panel-body">
<h4>{{publication.user.name}}</h4>
</div>
</div>
</div>
</div>
and this is the getPublications function that I have
getPublications(page){
this._publicationService.getPublications(this.token, page).subscribe(
response => {
console.log(response);
if(response.publications){
this.total = response.total_items;
this.pages = response.pages;
this.publications = response.publications;
if(page > this.pages){
this._router.navigate(['/home']);
}
}else{
this.status= 'error';
}
},
error =>{
var errorMessage = <any>error;
console.log(errorMessage);
if(errorMessage != null){
this.status = 'error';
}
}
);
}
If I make a console.log(response) it shows me the values of the array and the properties are correct (name,surname,email, text etc)
In the HTML code, when I do the loop for the publication's text <h4>{{publication.text}}</h4> it works and even if I use <h4>{{publication.user}}</h4> it shows a list of Objects.
I'm taking an online course and basically copying what the teacher does line by line but IDK why when I try to display name and surname properties, it shows the error that I told you
Thank you for your help.
I found the solution and is related to TS type system so basically I have a model object called publication.ts which includes:
export class Publication{
constructor(
public _id:string,
public text: String,
public file: String,
public created_at: String,
public user: String
){}
}
And the issue was related to the type for the property user so by changing its type to public user: any it worked and now it shows the required fields. Sorry for posting this without a deep search before ask for help. Newbie mistakes
Thanks for the help
You are subscribing to the data so there is a small delay in getting the data. Wrap the tag with a *ngIf to wait for the data to be available.
<div *ngIf="publications" id="publications">
<div *ngFor = "let publication of publications" class="item-publication">
<div class="panel panel-default">
<div class="panel-body">
<h4 *ngIf="publication && publication.user && publication.user.name">{{publication.user.name}}</h4>
</div>
</div>
</div>
</div>

Displaying object into HTML in Angular

sorry for the noob question.
I created an http request and retrieved some pokemon data and put it in an object called pokemon, like so:
export class AppComponent implements OnInit{
title = 'Pokedex';
apiURL = 'https://pokeapi.co/api/v2/pokemon/1';
pokemon = {};
constructor(private http: HttpClient){}
ngOnInit(): void{
this.http.get(this.apiURL).subscribe(data =>{
const pokemon = {
name: data['name'],
id: data['id'],
abilities: data['abilities'].map( ability => ability['ability']['name']),
types: data['types'].map( type => type['type']['name']),
image: data['sprites']['front_default']
}
console.log(pokemon);
When I console log the object, it outputs in the console fine.
However, when I try to display it in an html {{ pokemon }} it just returns [object, Object]
How can I get around this?
I have tried the methods suggested below.
{{pokemon.name}}, {{pokemon[name]}} and {{pokemon?.name} display a blank page.
{{ pokemon | json }} returns an empty object, in the form of {}.
Am I perhaps doing something else wrong?
You need to use the json pipe
<pre>{{ pokemon | json }}</pre>
OR
<div> Id: {{ pokemon.id }} </div>
<div> Name: {{ pokemon.name }} </div>
<div> Abilities:
<ul>
<li *ngFor="let ability of pokemon.abilities"> {{ ability }}</li>
</ul>
</div>
<div> Types:
<ul>
<li *ngFor="let type of pokemon.types"> {{ types }}</li>
</ul>
</div>
call property as {{pokemon?.name}}
You can't use object directly. You have to access object properties by either . (Dot) notation or object[property] way.
In your case, if you want to use the property of name then use
{{ pokeman.name }}
or
{{ pokeman[name] }}

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>

Not able to access json Object key

I have a json object as below:
Json
{error: false, message: [,…]}
Inside message:
{convid: "5aeab8a0e5dd7c55942a7ce7", recipient: "Akhil Sindhwani", seen: false, from: "Miti Desai",…}
convid : "5aeab8a0e5dd7c55942a7ce7" from : "Miti Desai" messages :
"asdsad" recipient : "Akhil Sindhwani" seen : false subject : "sasas"
updatedAt : "2018-05-03T07:22:09.367Z"
I am working in Angular and above is the response I get from http service.
Service function:
getUserMessages() {
console.log("getUserMessages");
this._mailingService.getMessages()
.subscribe(conversations => {
this.messageData = conversations
if (conversations) {
console.log( this.messageData);
this.messageData = conversations
}
})
, error => {
console.log("Error");
},
() => {
// THIS IS EXECUTED AFTER THE SUBSCRIBE COMPLETES
console.log( 'this.messageData');
console.log( this.messageData);
}
}
In code above I get a response in conversation which I get that json object.
I put that object in message data.
In html I tried to parse message data as follow:
<div id="messageMenu">
<ul>
<li class='msgBody' *ngFor = "let message of messageData.message">
<div class="msgListingContainer1">
<div class="senderImg">
<img src="../../../../assets/images/profile1.jpg">
</div>
</div>
<div style=" display:inline-block" class="msgListingContainer2">
<span style=" display:inline-block" class="senderName">{{message.recipients}}</span>
<span class="msgTimestamp">5:13pm</span>
<p class="msgheading"><span>Hey alex pretty cool new track you got..</span></p>
</div>
</li>
</ul>
</div>
But I get this error message:
MessageMenuComponent.html:6 ERROR TypeError: Cannot read property
'message' of undefined
I am trying to fetch a key from json and then loop it using ngFor directive it. It is simple, I have done this before.
Can anyone tell me what I am doing wrong?
Any help would be appreciated!
Update
Not sure how it worked.
Didn't change anything in component file.
Changed html to:
<div id="messageMenu">
<ng-container *ngIf="showConversations;else noCnvrstns" >
<ul>
<li class='msgBody' *ngFor = "let message of messageData">
<div class="msgListingContainer1">
<div class="senderImg">
<img src="../../../../assets/images/profile2.jpg">
</div>
</div>
<div style=" display:inline-block" class="msgListingContainer2">
<span style=" display:inline-block" class="senderName">{{message.recipient}}</span>
<span class="msgTimestamp">{{ message.updatedAt | date:'hh:mm a' }}</span>
<p class="msgheading">{{message.messages}}</p>
</div>
</li>
</ul>
</ng-container>
<ng-template #noCnvrstns>
<div class="noConversations">No conversations to show</div>
</ng-template>
</div>
Started getting response.
I didn't understand when messages were in message key of json object then how I able to fetch them out of conversations directly but working for me.
Not adding answer as question itself is ambiguous.
Thanks for help!
Better to use safe navigation ? in case of asnyc calls fetching data. it will not alow angular to throw an error.
Try this -
<li class='msgBody' *ngFor = "let message of messageData?.message">
Also at the time of declaration typecaste messageData: any.
Your JSON file is malformed.
How you can read here:
In JSON, keys must be strings, written with double quotes
Insert double quotes around your keys, this will probably fix the problem.

Iteration of Object of arrays of objects Angular4

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>