How to get properties of object from this HTTP response - html

I am trying to display the currency name or key like "USD", "AUD", "EUR" with their respective "last" and "buy" properties from this HTTP response:
and I just get back a list of "key" strings like this
but I can't figure out why my "key" is being returned as a string here.
It's making it difficult for me to programmatically access the properties for each currency
this is my dashboard.component.ts
prices;
bitcoinOwned;
ngOnInit(): void {
this.data.getPrice()
.pipe(map(result => {this.prices = result, console.log("result", result)
for (let key in result) {console.log( key)}
} ))
.subscribe();
}
my data.service
getPrice() {
var url = "https://blockchain.info/ticker";
return this.http.get(url);
}
and my template
<div>
{{ prices |json }}
</div>
<div>
USD last: {{ prices?.USD.last |json }} USD sell: {{ prices?.USD.sell |json }}
</div>
I can access the properties when I do it manually for each key like this but I need to iterate over the keys and do it more programmatically so any help would be appreciated!!

You may want to use Angular's KeyValuePipe.
Then, you can do something like this:
<div *ngFor="let item of prices | keyvalue">
{{item.key}} last: {{ item.value.last |json }} {{item.key}} sell: {{ item.value.sell |json }}
</div>

I think you can use Object.keys() on the object to return the key value.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Related

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] }}

Displaying Json array returnd from http get

I want to display content from the firebase I get the data from HTTP get request and I want to display it using ngFor
here is how i get the data
///a service
getMessages(){
return this.http.get('https://bigproject-dd88e.firebaseio.com/data.json')
.map((response:Response)=>{
const data: Message[]=response.json();
return data;
}
).catch(
(error:Response)=>{
return Observable.throw('something went wrong');
}
);
}
and here is my component
export class MessagesComponent implements OnInit {
Message=[];
constructor(private global:GlobalService) {
}
ngOnInit() {
this.GenaerateMessages();
}
GenaerateMessages(){
this.global.getMessages().subscribe(
Message=>this.Message=Message
);
}
}
and here is my HTML
<div *ngFor="let item of Message | keyvalue">
<p>{{item.value|json}}</p>
</div>
I get this on the screen
[ { "email": "loay-gohan#hotmail.com", "message": "loayy", "name": "loay", "phone": "123123123" } ]
[ { "email": "example#example", "message": "hi", "name": "..", "phone": "123123" } ]
how can I reach the inside fields name, message, phone...
it looks like eachitem.value contains one array with one object. If this is a case you can reach it like this:
<div *ngFor="let item of Message | keyvalue">
<div>EMAIL: {{ item.value[0].email }}</div>
<div>MESSAGE: {{ item.value[0].message }}</div>
<div>NAME: {{ item.value[0].name }}</div>
<div>PHONE: {{ item.value[0].phone }}</div>
<pre>{{ item.value | json }}</pre>
</div>
If item.value array has more than one object you might want to loop it wit additional inner ngFor
You do not use value.key. Don't you need it?

Getting 'matches' array data within a 'query' from an API and displaying the information

I am having trouble displaying data from querying an API endpoint. The error message is ERROR TypeError: Cannot read property 'name' of undefined. I understand that I have to jump to display the "matches" array but having a lot of difficulty doing so.
This is what the url returns:
{
"query": "An",
"matches": [
{"name": "Jane Hardman", "id": "248086622848468681706182205280565550732"},
{"name": "Gary Aldan", "id": "246529435182620212343890064029443600078"}
]
}
This is my meeting-handler.service.ts file:
constructor(private _httpClient: HttpClient) {}
getListOfEmployees(query: string = '') {
return this._httpClient.get(
`${this.meetingUrl}/employees?q=${query}`);
}
This is my meeting-form.component.ts file:
export class MeetingFormComponent implements OnInit {
employees;
constructor(private _meetingService: MeetingHandlerService) {
this._meetingService.getListOfEmployees('An').subscribe(
res => this.employees = res
)
}
And finally this is my meeting-form.component.html file:
<div *ngFor="let employee of employees"></div>
<p>{{ employee.name }}</p>
The name is inside this.employees.matches and you have to iterate on the matches field.
Can you try this :
<div *ngFor="let employee of employees?.matches.name"></div>
<p>{{ employee }}</p>
Can you try to edit your get request ?
return this.http.get(`${this.meetingUrl}/employees`, {
params: new HttpParams()
.set('q', query)
})
I checked your stackblitz and I found a typo here :
<div *ngFor="let employee of employees?.matches.name"></div>
<p>{{ employee.name }}</p>
Why are you using {{ employee.name }} ? You iterate on name so you employee is already a name.
Try this :
<div *ngFor="let name of employees?.matches.name"></div>
<p>{{ name }}</p>
<div *ngFor="let employee of employees">
<p>{{ employee.name }}</p>
</div>
Moved the closing tag.

Can't Access JSON Properties Of Firestore Data With String Interpolation

I can't access the properties of my Firestore document during string Interpolation. The regular JSON output works fine though. Here's the code:
Working
<h3>{{ teacher | async | json }}</h3>
Output:
Not working
<h3>{{ teacher.name | async | json }}</h3>
and
<h3>{{ teacher.name | async }}</h3>
Output:
Typescript code
interface Teacher {
name: string;
}
teacherDoc: AngularFirestoreDocument<Teacher>;
teacher: Observable<Teacher>;
var placeToSearch = 'Teachers/'+this.selectedTeacher;
this.teacherDoc = this.afs.doc(placeToSearch);
this.teacher = this.teacherDoc.valueChanges();
You're just slightly off with the async pipe. The object needs to be unwrapped first, then you call it's properties. It should look like:
{{ (teacher | async)?.name }}
Or better yet, set a template variable to avoid using the async pipe over and over:
<div *ngIf="teacher | async as t">
{{ t.name }}
{{ t.field }}
{{ t.whatever }}
</div>
Your interface should have both name and field
interface Teacher {
name: string;
field: string;
}
<h3>{{ teacher?.name | async }}</h3>

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;
}
});