Angular - how to get result of a JSON object?
From the api data that you are showing, I see that you are assigning this.coins
with the object but not an array. You should first convert it into an array and then assign it to this.coins
.
getCoins() {
this.coinsService.getCoins().subscribe(
data => {
this.coins = [];
for(let key in data){
this.coins.push(data[key]);
}
});
}
Or else you could also do this way to convert object to array.
getCoins() {
this.coinsService.getCoins().subscribe(
data => {
this.coins = [];
Object.keys(data).map((key)=>{ this.coins.push(data[key]) });
});
}
In your service file
getCoins() {
return this.http.get(this.urlBase).pipe(map(res => res = res.json()['data']))
}
Working DEMO
How to read a JSON object response from GET request in Angular 9?
Apparently, it was an async reply so can be solved using the async-wait method.
This is how I changed the code in service:
latestRates(base: string = "USD"): Promise<any> {
//return this._http.get('http://data.fixer.io/api/latest? access_key='+this.api_key+'&base='+base).toPromise();
return this._http.get('https://api.exchangeratesapi.io/latest?base='+base).toPromise();
}
And the receiving function looks like:
data:any;
async requestData(base) {
this.data = await this.forex.latestRates(base);
}
How to get data from JSON object to Angular?
You can add logic to check result is array or not, if not convert it to array.
this._companyService.getCompany()
.subscribe(data => {
if(!Array.isArray(obj)){
this.company = [data]
}else{
this.company = data;
}
},
error => this.errorMsg = error);
How to access data in JSON response in Angular 8?
You are getting undefined because of
const fault = data[0];
const fault2 = data[1];
as your data is object not array therefore fault[0] does not exists
try
const fault = data.faults[0];
const fault2 = data.faults[1];
How to return specific fields from a JSON object array in angular http service as response
getdata(): Observable<User[]>{
return this.http.get<User[]>('https://jsonplaceholder.typicode.com/users').pipe(
map((data: User[])=> {
// just map the data
return data.map(u => ({id: u.id, name: u.name}))
})
)
}
How to get result from json object with angular js?
You can't run SQL queries on JSON out-of-the-box, so let's work through it in JavaScript.
We have some data in an array, let's call it people
:
let people = [
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
];
Now, let's filter it down based on their gender
and district
like in your query:
let filtered = people.filter(p => (p.district === "LA") && (p.gender === "Female"));
Now instead of using COUNT
, we can just check the length
property of our filtered array:
let count = filtered.length;
We can abstract this code away into a nice function which will do the work for us:
let getCount = (array, predicate) => {
return array.filter(predicate).length;
};
And we can then use this function like so:
let people = [
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
];
getCount(people, p => p.district === "NY" && p.gender === "Male"); // 1
Note that based on your example data, the count is 0
as you have nobody in the district "LA"
.
Angular 5 display result from JSON response
Try this. Make sure you import following import on top of the component
import 'rxjs/Rx';
or
import 'rxjs/add/operator/map'
getData(){
this.http.get('https://api.openweathermap.org/data/2.5/forecast?id=3362024&APPID=bbcf57969e78d1300a815765b7d587f0')
.map(res=>res.json()).subscribe(data => {
this.items = data;
console.log(this.items);
for(var i = 0; i < this.items.list.length; i++){
this.min = this.items.list[i].main;
console.log(this.min);
}
});
}
WORKING DEMO
angular 13 - insert incoming json object into model
I'll start off by saying you have quite a strange implementation.
This goes in your component :
public workflows: WorkflowListModel[] = [];
constructor(private workflowService: WorkflowListService) {
}
ngOnInit(): void {
this.workflowService.getWorkflowDefinitions().subscribe(
(data: WorkflowListModel[]) => this.workflows = data
);
}
- The service should not be public, you should not be able to access it from the HTML template, only from the component.
- I would've created a private function that would get the workflows and call that function in the
ngOnInit()
- You might want to do error handling in case of an error
This goes in your service :
public getWorkflowDefinitions(): Observable<WorkflowListModel[]> {
return this.httpClient.get<WorkflowListModel[]>(`${this.apiUrl}/services/workflows`);
}
- I used observables so you can retrieve the object type, again you had a strange implementation that I have never seen before
- You were esentially retrieving an object of type
any
since you didn't specified anything - Why bother creating a variable with the API URL when you are only using it once?
This goes in your model class
export class WorkflowListModel {
public id: any;
public definitionId: any;
public name: any;
public displayName: any;
public description: any;
public version: any;
public persistenceBehavior: any;
public isPublished: any;
public isLatest: any;
constructor() {
}
}
any
means any type, so string | any
it's pretty much useless, but I wouldn't use any
since most likely there are only numbers and strings that you are working it
Can I return raw json response in angular2
Yes off course you can !!
Actually angualar2 returns Response in the form of Observable
instead of promise Like in angular1.x , so in order to convert that observable into raw Json format we have to use the default method of angular2 i.e
res.json()
There are no of method apart from .json()
provided by angular which can be described here for more info.
methods include
- res.text()
- res.status
- res.statusText
etc
updatehttps://angular.io/docs/ts/latest/api/http/index/Response-class.html
use your code like this
return this.http.post(URL, body, options)
.map(res => {return res.json()})
.catch(this.handleError);
}
Related Topics
How to Create a Remember Me Function in Login Without Using Form in JavaScript or Jquery
Javascript and Getelementbyid for Multiple Elements With the Same Id
How to Stop Parsefloat() from Stripping Zeroes to Right of Decimal
Javascript - How to Remove All Extra Spacing Between Words
Make a Clickable Link With Onclick But Without Href=#
How to Prevent the Keyboard from Popping Up on Mobile Devices
Sticky Header Smoothing Scroll Down
Google Charts: Move Legend Position
Charts.Js Graph Not Scaling to Canvas Size
How to Remove Time from Datetime in SQL
Have a Div Move on Scroll Up and Down
Label and Input Fields on the Same Line
Array Push Is Overwriting the Existing Array
Merge Array of Objects by Same Key-Value