Print JSON response from REST api in ionic - html

I'm trying to print a JSON response that I get from a RESTful API request like that:
products:Observable<any>;
constructor(public navCtrl: NavController, private backgroundGeolocation: BackgroundGeolocation, public zone: NgZone, private auth: AuthService, public httpClient: HttpClient)
{
this.products = this.httpClient.get('http://127.0.0.1:8000/product');
}
It works fine, indeed if I print result in console:
this.products
.subscribe(data => {
console.log('my data: ', data);
});
the data is right.
But now, I don't know how to print them out onto a HTML page. I've tried this but it doesn't work:
<ion-list>
<ion-item *ngFor="let p of (products | async)?.results">{{ p.productName}}
</ion-item>
</ion-list>
Are there other ways to resolve the problem?
My JSON response is like that:
0: Object { idProduct: "1", productName: "Pasta", purchased: "0" }
​
1: Object { idProduct: "2", productName: "latte", purchased: "0" }
I have resolved the trouble. I want to post the solution to help other users in this bad situation.
Solution is so simple. I created a new typescript file called: 'rest-service' made up by:
#Injectable()
export class RestServiceProvider {
constructor(public http: HttpClient) {
console.log('Hello RestServiceProvider Provider');
}
getUsers() {
return new Promise(resolve => {
this.http.get('http://127.0.0.1:8000/product').subscribe(data => {
resolve(data);
}, err => {
console.log(err);
});
});
}
}
Now, in home.ts I've done that:
getUsers() {
this.restProvider.getUsers()
.then(data => {
this.products = data;
console.log(this.products);
});
}
And then, in the constructor, that:
this.getUsers();
In HTML side instead, the solution is very very simple:
<ion-item *ngFor="let p of products"> {{ p.productName }}
However, thanks to all

please try to convert products to array object. That may fix your problem.
this.products = this.products.json();

UPDATE
Looks like you found the solution. Normally I don't prefer doing *ngFor directly at a function
<!-- DON'T DO THIS -->
<ion-item *ngFor="let item of someFunction()">
but rather define a variable above the constructor, and then assign data. A separate file wouldn't be necessary, but can be useful if you are doing the same request over and over.
TypeScript
items: Array<any> = [];
constructor() {
// ...
}
ionViewDidLoad() {
this.http.get('https://someurl.com/data').subscribe((data: any) => {
this.items = data;
}).catch(err => console.error('Something went wrong: ', err));
}
HTML
<ion-item *ngFor="let item of items">
{{ item.name }}
</ion-item>
Old answer
What happens if you just do following?
<ion-item *ngFor="let p of products">
Any reason why you are trying to access .results on the products-array?
If you get any errors in the console, please share them with us.

Related

How to list objects in an object in html?

I'm writing app in Angular and Node.js. I have an object (order) that has a list of objects (items) that also contain objects (list of product id). I want to display them all in an html file. Please help me.
html file:
<div *ngIf="order">
<div *ngFor="let item of order.items"> // <- it does not work
<a>{{order.items}}</a> // <--
</div>
</div>
ts file:
export class AdminOrderItemComponent implements OnInit {
order: Order;
orderId;
constructor(private orderService: OrderService, private route: ActivatedRoute) { }
ngOnInit() {
this.route.paramMap
.subscribe(params => {
this.orderId = [params.get('id')];
this.getOrderById();
});
}
getOrderById() {
this.orderService.getOrderById(this.orderId).subscribe(
res => {
this.order = res;
},
err => console.log(err)
);
}
}
order interface:
export interface Order {
_id: any;
shipping: string;
userData: {};
sum: number;
items: {};
}
The ngFor iterates over the items of a collection. If you take a look at your model, you will realize that items is an object ({}), not an array ([]).
Your best bet is transforming the object received from your node.js backend to match your needs or (preferably I think) make your node.js model treat items as a collection as well which seems more appropriate.
Answer from #kg99:
Key: {{item.key}} and Value: {{item.value}}

How to get array json instead of object json

I made some autocomplete feature, and it required some array method. I want to use array json as my API instead of object json.
Since filter method only works for array. I have to use array json[] as my API url, but my API is an object json{} file. How to make it as an array?
I tried with some array json API. The code works with array json, but it doesn't work with object json.
HTML:
<mat-autocomplete #auto="matAutocomplete" [displayWith]="getOptionText">
<mat-option *ngFor="let option of (filteredOptions | async)" [value]="option">
{{ option.make }}
</mat-option>
</mat-autocomplete>
Service ts:
#Injectable({
providedIn: 'root'
})
export class Service {
constructor(private http: HttpClient) { }
opts = [];
getData() {
return this.opts.length ?
of(this.opts) :
this.http.get<any>('https://api.myjson.com/bins/15psn9').pipe(map(data => this.opts = data));
}
}
Component ts:
constructor(private service: Service) { }
ngOnInit() {
this.filteredOptions = this.searchForm.controls['customerId'].valueChanges.pipe(
startWith(''),
debounceTime(100),
switchMap(value => value.length >= 3 ? this.doFilter(value) : [])
);
}
doFilter(value) {
return this.service.getData()
.pipe(
map(response => response.filter((option: { make: { toLowerCase: () => { indexOf: (arg0: any) => number; }; }; }) => {
return option.make.toLowerCase().indexOf(value.toLowerCase()) === 0;
}))
);
}
getOptionText(option) {
return option.make;
}
I expected API JSON is array or autocomplete feature works.
In your Service try using: from instead of. Check this docs.
Here is a working stackblitz based on your code.

JSON data not displaying in Ionic HTML file

I have got my data from my API and it is logged in the console. However, I am unable to access it through my HTML file. I'm not sure why it isn't working? (Looked at other questions and still no joy).
ts file
patients: [];
constructor(private viewService: ViewPatientService ) { }
ngOnInit() {
this.viewService.viewPatient().subscribe(data => {
console.log(data);
});
html file
<ion-item *ngFor="let patient of patients">
Name: {{patient.patients.data[0].FirstName}}
</ion-item>
Please note data should hold the patients array, if not add the property as needed.
patients: [];
constructor(private viewService: ViewPatientService) { }
ngOnInit() {
this.viewService.viewPatient().subscribe(data => {
console.log(data);
this.patients = data
});
}
You haven't assigned the value to patients array
patients: [];
constructor(private viewService: ViewPatientService ) { }
ngOnInit() {
this.viewService.viewPatient().subscribe(data => {
**this.patients = data;**
console.log(data);
});
patients: any;
constructor(private viewService: ViewPatientService ) { }
ngOnInit() {
this.viewService.viewPatient().subscribe(data => {
this.patients = [data];
console.log(data);
});

How do i pass data received from angular to html front-end?

this is my angular service:
#Injectable()
export class ApiService {
private get_msg_url: string = "http://localhost:3000/getmessages";
constructor(private http:HttpClient) { }
getMessage(): Observable<IPosts> {
return this.http.post<IPosts>(this.get_msg_url,{"data":"data1"});
}
}
this is my message.component.ts :
export class MessagesComponent implements OnInit {
data = [];
iposts: IPosts[];
constructor(private apiSerivce: ApiService) {
}
getMessage(): void {
this.apiSerivce.getMessage()
.subscribe(data1 => this.data.push(data1));
}
ngOnInit(): void {
this.getMessage();
console.log(this.data);
}
}
this is my posts.ts:
export interface IPosts {
timestamp : number;
message_content : string;
message_link :string;
tags : string[] ;
}
this is messsage.component.html:
<p>Json data {{data}} </p>
whenever the code is run i can see the required data in console of chrome but there is no data shown on page.
the data received on console is of form:
[]
0:
message: Array(3)
0: {timestamp: 1522072833748,
tags: Array(2), _id: "5aacb7cc0281b558debacf26",
message_link:"String"
}}
the problem is, that you try to print an array, instead of the elements.
<p>Json data {{data}} </p>
change this to something like this:
<p *ngFor="let element of data; index as i">
Json data #{{i}}: {{element]]
</p>
As I can see, data is an array. you can display the raw content of an array with the pipe json : {{data | json}}
However I am not sur what you want to do with a json displayed in your html.
The problem is your output data is an array, not an element.
Try something like this,
<ul *ngFor="let element of data">
<li>{{element}}</li>
</ul>

Ionic 2 consuming json issue

I'm using Ionic 2 and i couldn't consume a json. for some reason it throws an error.
Here is my updated code.
sales-service.ts
#Injectable()
export class SalesService {
constructor(public http: Http) {
this.http = http;
}
retrieveSalesData() {
return this.http.get("http://api.randomuser.me/?results=10");
}
}
sale.ts
#Component({
selector: 'page-sale',
templateUrl: 'sale.html',
providers: [SalesService],
})
export class SalePage {
data:any;
constructor(data: SalesService) {
this.data=data.retrieveSalesData().subscribe(data =>{
this.data=JSON.parse(data._body).results;
console.log("Inside Subscribe (All Elements):"+ this.data);
console.log("Inside Subscribe (Single Element):"+this.data[1].name.first);
});
console.log("Inside Constructor (All Elements):"+ this.data);
console.log("Inside Constructor (Single Element):"+ this.data[1].name.first);
}
ionViewDidLoad() {
console.log("Inside IonView (All Elements):"+ this.data);
console.log("Inside IonView (Single Element):"+this.data[1].name.first);
}
}
sale.html -- This is not the issue so i've commented the code
<ion-list>
<ion-content padding>
<!--<ion-list>
<ion-item *ngFor="let item of data">
<h2>{{item.name.first}}</h2>
</ion-item>
</ion-list>-->
</ion-content>
Here is my error:
I think i found the issue, but don't know how to clear it.
All elements are received in subscribe, but not in constructor and as well as in IonView. Please advise.
Here is my ionic info
I don't care of your update1.
I assume you get response object in this.data object.
If you are dealing with latest angular2 version, make sure you use let keyword instead of # as show below,
<ion-item ngFor="let person of data"> //<<<===here
<p>{{person?.name.first}}</p> //<<<=== (?.) operator is used as you deal with async call.
</ion-item>
</ion-list>
change your sales-service.ts file like bleow
#Injectable()
export class SalesService {
salesData:any;
constructor(public http: Http) {
//this.http = http;
this.salesData = [];
}
retrieveSalesData() {
this.http.get('https://randomuser.me/api/?results=10')
.subscribe(salesData => {
this.salesData = salesData.result;
});
}
}
inside your html
<ion-list>
<ion-item *ngFor="let person of data">
<p>{{person.name.first}}</p>
</ion-item>
</ion-list>
</ion-content>
Try the follwoing
sales-service.ts
#Injectable()
export class SalesService {
salesData:any;
constructor(public http: Http) {
this.http = http;
this.salesData = null;
}
retrieveSalesData() {
return this.http.get('https://randomuser.me/api/?results=10')
}
}
sale.ts
#Component({
selector: 'page-sale',
templateUrl: 'sale.html',
providers: [SalesService]
})
export class SalePage {
data:any;
constructor(private salesService: SalesService) {
}
ionViewDidLoad() {
this.salesService.retrieveSalesData()
.subscribe(salesData => {
this.data= salesData;
});
}
}
Try upgrading your app-scripts:
npm install #ionic/app-scripts#latest
Their previous version was missing a JSON plugin which they just added to the rollup process.
I found the answer that's working for me.
This is what i did,
public data:Users[]=[];
constructor(public pdata: SalesService) {
pdata.retrieveSalesData().subscribe(data =>{
JSON.parse(data._body).results.forEach(element => {
this.data.push(
new Users(element.name.first)
);
});
});
}
export class Users {
name: string;
constructor(_name: string) {
this.name = _name;
}
}
This works for me. If there is an alternative and elegant way. please feel free to update the answer. Thank you for all your time.