Not able to display data from post in ionic - html

I'm trying to get data that I get from a post call and display in my html page in ionic.
My Ts code is
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '#angular/common/http';
#IonicPage()
#Component({
selector: 'page-fashion',
templateUrl: 'fashion.html',
})
export class FashionPage {
users: any;
body: Object = {
"id": 1014,
"filter": null,
"lat": 13.05831,
"lng": 80.21195,
"mapRadius": 5,
"pageSize": 50,
"pageStart": 1,
"priceRangeFrom": 0,
"priceRangeTo": 100000
};
constructor(public navCtrl: NavController, public navParams: NavParams, public httpClient: HttpClient) {
this.users = this.httpClient.post('myapi',this.body);
this.users.subscribe(data => {
this.users = data;
console.log('my data: ', data);
console.log("the users data ------------>",this.users);
})
}
}
And my html page is
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Fashion</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list inset>
<ion-item *ngFor="let user of (users | async) ">
<h2>{{user.Name}}</h2>
<p>Price : {{user.Price}}</p>
</ion-item>
</ion-list>
</ion-content>
The error is InvalidPipeArgument: '[object Object]
but i am also getting the data before the error message comes, so when i click on close on the above image i am getting my data, but i need to get it as soon as get into the page
EDIT1: I am Getting the data only when i switch to a different tab and come back to this
EDIT2: Guys a I forgot to mention what my api returns, It gives me [34]
i.e.
[{
....
},
..
].

There is an error in your aync pipe declaration it should be like below . Also you are using the same users property to create the Observable and store the data. Create a new property to store the data.
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Fashion</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list inset>
<ion-item *ngFor="let user of userData | async ">
<h2>{{user.Name}}</h2>
<p>Price : {{user.Price}}</p>
</ion-item>
</ion-list>
</ion-content>
edit : create a new property like userData:any[] = [] in your component as use it like below -
export class FashionPage {
users: any;
userData:any[] = []
body: Object = {
"id": 1014,
"filter": null,
"lat": 13.05831,
"lng": 80.21195,
"mapRadius": 5,
"pageSize": 50,
"pageStart": 1,
"priceRangeFrom": 0,
"priceRangeTo": 100000
};
constructor(public navCtrl: NavController, public navParams: NavParams, public httpClient: HttpClient) {
this.users = this.httpClient.post('myapi',this.body);
this.users.subscribe(data => {
this.userData = data;
console.log('my data: ', data);
console.log("the users data ------------>",this.userData);
})
}
}

Initialize users: any; as users = []; since async requires an
observable or an array
Also change the variable name of subscription,
this.users = this.httpClient.post('myapi',this.body);
to,
this.userResult = this.httpClient.post('myapi',this.body);
change html to <ion-item *ngFor="let user of users | async ">
HTML:
<ion-item *ngFor="let user of users | async ">
<h2>{{user.Name}}</h2>
<p>Price : {{user.Price}}</p>
</ion-item>
So TS:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '#angular/common/http';
#IonicPage()
#Component({
selector: 'page-fashion',
templateUrl: 'fashion.html',
})
export class FashionPage {
users: any;
....
constructor(public navCtrl: NavController, public navParams: NavParams, public httpClient: HttpClient) {
this.userResult = this.httpClient.post('myapi',this.body);
this.userResult.subscribe(data => {
this.users = data;
console.log('my data: ', data);
console.log("the users data ------------>",this.users);
})
}
}

The api returns me [34], i.e. array of 34 objects in it.
I needed a separate variable to store the data and to call the api.
So the code that works to get me the data is
HTML code
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Fashion</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list inset>
<ion-item *ngFor="let user of userData">
<h2>{{user.Name}}</h2>
<p>Price : {{user.Price}}</p>
</ion-item>
</ion-list>
</ion-content>
TS code
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '#angular/common/http';
#IonicPage()
#Component({
selector: 'page-fashion',
templateUrl: 'fashion.html',
})
export class FashionPage {
users: any;
userData = [];
body: Object = {
"id": 1014,
"filter": null,
"lat": 13.05831,
"lng": 80.21195,
"mapRadius": 5,
"pageSize": 50,
"pageStart": 1,
"priceRangeFrom": 0,
"priceRangeTo": 100000
};
constructor(public navCtrl: NavController, public navParams: NavParams, public httpClient: HttpClient) {
this.users = this.httpClient.post('myapi',this.body);
this.users.subscribe(data => {
this.userData = data;
console.log('my data: ', data);
console.log("the users data ------------>",this.userData);
})
}
}
You guys are always wonderful,this community has never failed me once...Thanks a million to all for your valuable time to get me the answer!!!!!!!!

Related

Access item in JSON array and display objects data

I am trying to use weather API and get open data for first object in JSON array.Instead i get all objects.How can i access for example first object in JSON array?Also how to make so the data will show instead of [object, object].
Right now it looks like this:
It should look more like this:
"name":"msl",
"levelType":"hmsl",
"level":0,
"values":[
1031
Here is my code:
HTML:
<ion-header>
<ion-navbar>
<ion-title>New App</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding class="no-scroll">
<ion-grid>
</ion-row>
<button ion-button (click) = "getData()">Get Data</button>
<ion-row>{{result.timeSeries}}</ion-row>
<ion-row>
<ion-col>
</ion-grid>
</ion-content>
TS code:
import { Component, state } from '#angular/core';
import { NavController, AlertController, Platform, Alert} from 'ionic-angular';
import { MapPage } from '../map/map';
import { NewGamePage } from '../new-game/new-game';
import {AchievmentPage} from '../achievment/achievment';
import {DailyRoutesPage}from '../daily-routes/daily-routes';
import { LocalNotifications } from '#ionic-native/local-notifications'
import { PhonegapLocalNotification } from "#ionic-native/phonegap-local-notification";
import { Push, PushObject, PushOptions} from '#ionic-native/push'
import { HttpClient } from "#angular/common/http";
import { Observable } from "rxjs/Observable";
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
result: any = [];
data: Observable<any>;
constructor(public navCtrl: NavController, public alertCtrl: AlertController, private platform: Platform, private localNotification: LocalNotifications, private notiPhoneGap: PhonegapLocalNotification, public http: HttpClient) {
}
getData(){
var url = `https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/16.158/lat/58.5812/data.json`;
this.data = this.http.get(url);
this.data.subscribe(data=>{
this.result = data;
})
}
}
You can "stringify" the data using the built-in JSON.stringify function. You will need to specify the padding in the third parameter.
Ignore the CORS proxy, I just used it to bypass the same-origin-policy.
var apiUrl = 'https://opendata-download-metfcst.smhi.se/api';
var apiPointUrl = `${apiUrl}/category/pmp3g/version/2/geotype/point`;
// Builds an API url to get a point at a set of coordinates.
function getPointData(longitude, latitude) {
return `${apiPointUrl}/lon/${longitude}/lat/${latitude}/data.json`;
}
// Wrapping with a CORS proxy so that there is no issue with Same-Origin-Policy
var requestQuery = `https://cors.io/?${getPointData(16.158, 58.5812)}`;
$.getJSON(requestQuery, (result, status, xhr) => {
// Display the first two hours in the timeSeries.
console.log(JSON.stringify(result.timeSeries.slice(0, 2), null, 2));
});
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Runtime Error = object is not a function

I'm developing my first aplication with Ionic, and would like to display the firebase data at home.html, but when I start the serve show me this message in browser:
object(...) is not a function
I create this code at home.ts:
import { Component } from '#angular/core';
import { NavController, IonicPage } from 'ionic-angular';
import { ShoppingListService } from '../../services/shopping-list/shopping-list.service';
import { AjaxObservable } from 'rxjs/observable/dom/AjaxObservable';
import { Observable } from 'rxjs/Observable';
import { Item } from '../../models/item/item.model';
#IonicPage()
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
shoppingList$ : Observable <Item[]>;
constructor(public navCtrl: NavController, private shopping:ShoppingListService) {
this.shoppingList$ = this.shopping
.getShoppingList() //pega a lista do banco de dados
.snapshotChanges() //chave e valor das infos do bd
.map(changes => {
return changes.map(c => ({
key: c.payload.key,
...c.payload.val(),
}));
});
}
}
After this, I create the home.html:
<ion-content padding>
<ion-list>
<ion-list-header>
Items
</ion-list-header>
<ion-item *ngFor="let item of shoppingList$ | async">
{{item.nomecontratante}}
</ion-item>
</ion-list>
</ion-content>
Thanks for help me!

Load Data from mysql to Ionic

Hi Developpers i am working in projet where i need to load data from database and show it in the page in ionic , i didn't found any problem but it didn't work too
here is the page of getting data from database
<?php
include("db.php");
header("Access-Control-Allow-Origin: *");
$query = "select * from etudiant";
$result = $db->query($query);
$res['etudiant'] = [];
while ($etud = $result->fetch_assoc()) {
$res['etudiant'][] = $etud;
}
echo json_encode($res);
and this is the component page
import {Component} from '#angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {EtudiantProvider} from "../../providers/etudiant/etudiant";
#IonicPage()
#Component({
selector: 'page-etudiant',
templateUrl: 'etudiant.html',
})
export class EtudiantPage {
public isSearchbarOpened = false;
etudiant:String;
constructor(public navCtrl: NavController, NavParams: NavParams, public etudiantProvider: EtudiantProvider) {
}
ngOnInt() {
this.etudiantProvider.getEtudiant().subscribe(
data => (
this.etudiant=data.etudiant.nom
),
error => {
console.log(error);
}
)
}
}
and here is my providers
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class EtudiantProvider {
url: string;
constructor(public http: Http) {
console.log('Hello Provider');
this.url = "http://localhost/eportfolio/api.php";
}
getEtudiant(){
return this.http.get(this.url+"?action=getEtudiant").map(res => res.json())
}
}
and this is the page where i need to show data
<ion-list [virtualScroll]="etudiant" [approxItemHeight]="'250px'">
<ion-item *virtualItem="let etud">
<ion-avatar item-start id="avatar">
<p id="letters">AF</p>
</ion-avatar>
<h1>{{etud.nom}}</h1>
<button ion-item clear no-lines>{{etud.nom}}</button>
<button ion-item clear no-lines>{{etud.prenom}}</button>
</ion-item>
</ion-list>
export class etudiantEntity{
constructor(public nom: string, public prenom: string){}
}
create a class like that
and modify your Etudiant
export class EtudiantPage {
public isSearchbarOpened = false;
etudiant:etudiantEntity;
...etc
This might solve your problem

Show specific data for the clicked element using popover

when I retrieve data from a json file, in the *ngFor displays all the values in the popover, but I need a specific popover to display based only on the data for selected/clicked weapon. Here is my code any help would be greatly appreciated. Thank you again for your help
Home
import { Component } from '#angular/core';
import { NavController, ViewController, PopoverController, Events} from 'ionic-angular';
import { RestProvider } from './../../providers/rest/rest';
import { PopupPage } from './../../pages/popup/popup';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
weapons: any;
errorMessage: string;
constructor(public navCtrl: NavController, public rest: RestProvider,
public popoverCtrl: PopoverController) {
}
ionViewDidLoad() {
this.getweapons();
}
getweapons() {
this.rest.getweapons()
.subscribe(
weapons => this.weapons = weapons,
error => this.errorMessage = <any>error);
}
presentPopover(myEvent)
{
let popover = this.popoverCtrl.create(PopupPage);
popover.present({
ev: myEvent
});
}
}
home.html
<ion-content>
<ion-searchbar [(ngModel)]="terms"></ion-searchbar>
<ion-item>
</ion-item>
<ion-list>
<button ion-item (click)="presentPopover($event)">
<ion-item *ngFor="let c of weapons?.weapon_category?.weapons | search : terms">
<h2>{{c.name}}</h2>
</ion-item>
</button>
</ion-list>
</ion-content>
popup.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, ViewController, Events} from 'ionic-angular';
import { RestProvider } from './../../providers/rest/rest';
import { HomePage } from './../../pages/home/home';
/**
* Generated class for the PopupPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-popup',
templateUrl: 'popup.html',
})
export class PopupPage {
rangeSettings = 20;
weapons: any;
errorMessage: string;
constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public rest: RestProvider) {
alert('inside the popup');
}
close() {
this.viewCtrl.dismiss();
}
getweapons() {
this.rest.getweapons()
.subscribe(
weapons => this.weapons = weapons,
error => this.errorMessage = <any>error);
}
ionViewDidLoad() {
this.getweapons();
}
}
popup.html
<ion-header>
<ion-navbar>
<ion-title>popup</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item *ngFor="let c of weapons?.weapon_category?.weapons">
<h2>{{c.damage.base}}</h2>
<h2>{{c.damage.chest0}}</h2>
<h2>{{c.damage.chest1}}</h2>
<h2>{{c.damage.chest2}}</h2>
<h2>{{c.damage.chest3}}</h2>
<h2>{{c.damage.head1}}</h2>
<h2>{{c.damage.head2}}</h2>
<h2>{{c.damage.head3}}</h2>
</ion-item>
<ion-item>
<ion-range min="0" max="80" [(ngModel)]="rangeSettings" color="danger" pin="true" snaps="true" disabled=true></ion-range>
</ion-item>
</ion-list>
</ion-content>
Popover doesn't need to hit the REST call again. You can pass the chosen weapon to the popover as a parameter.
Change your function to accept a weapon (make sure you change the code in the HTML too)
presentPopover(myEvent, weapon)
And send it to the popover controller this way:
this.popoverCtrl.create(PopupPage, weapon);
Now in your popup.ts, decleare a weapon object in your class,
weapon : any;
and grab the weapon from the navParams in your constructor
this.weapon = this.navParams.data;
Change your <ion-item> in popup.html to display the selected one.
<ion-item>
{{weapon.damage.base}}
...
</ion-item>

DataApi data not found (not display in Html) in Ionic2

I'm developing an application for Ionic 2.I'm taking pictures from JSON, and I list the data in the console.log.However they're not displayed in HTML.Error (GET http://ukopuz.com/[object%20Object] 404 (Not Found) )Where did I go wrong?
data-api.service.ts
import {Injectable} from '#angular/core';
import {Http,Response} from '#angular/http';
#Injectable()
export class DataApi {
private url = 'http://ukopuz.com/api/2';
constructor(private http:Http){
}
getReferenceData(){
return new Promise(resolve =>{
this.http.get(`${this.url}`)
.subscribe(res => resolve(res.json()))
});
}
}
reference.html
<ion-content class="content">
<ion-grid>
<ion-row *ngFor="let ref of reference">
<ion-col col-4 >
<img src="http://ukopuz.com/{{ref}}" >
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
reference.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams,ModalController } from
'ionic-angular';
import {DataApi} from '../../app/dataapi/data-api.service';
import {Http, HttpModule} from '#angular/http';
import {ModalPage} from '../modal/modal';
#IonicPage()
#Component({
selector: 'page-references',
templateUrl: 'references.html',
})
export class ReferencesPage {
reference : any;
constructor(public navCtrl: NavController, public navParams:
NavParams,public dataApi:DataApi,
public http:HttpModule,public modalCtrl:ModalController) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad ReferencesPage');
this.dataApi.getReferenceData().then(data =>
this.reference = data);
console.log("data:"+ this.reference );
console.log("viewload");
}
}
data.json
[
{
"3": "/img/ref/adana.png",
"4": "/img/ref/ajans.png",
"5": "/img/ref/akp.jpg",
"6": "/img/ref/akp.png",
"7": "/img/ref/akpgenclik.png",
"8": "/img/ref/ankara.png",
"9": "/img/ref/arnavut.png",
"10": "/img/ref/aydin.png"
}
]
I have checked your return json from API, it is not returning any data due to this you are getting any response in your .html page
Check the API page