Ionic 2 public object array doesn't display in a view - ionic2

I have a script that retrieve some datas and store it in an array :
export class ProductsByArea {
public products: any;
public area: any;
constructor(public navCtrl: NavController,
public navParams: NavParams,
private easyStockService: EasyStockService,
private imageProvider: ProductImageProvider,
private platform: Platform
)
{
//this.area = navParams.get('area');
this.easyStockService.getArea(navParams.get('area')).then((doc) => {
this.area = doc;
this.getProducts(this.area._id).then((products) => {
let datas: any;
datas = products;
this.products = datas;
});
});
}
private getProducts(area: any){
let datas: any = [];
let products: Array<any> = [];
return new Promise((resolve) => {
this.easyStockService.getProducts(area).then((results) => {
datas = results;
let uploadDirectory = this.imageProvider.getUploadDirectory();
// Boucle sur les produits pour récupérer les données cohérentes
datas.forEach((data) => {
let product: any = {};
product.ean = data._id;
product.title = data.title;
if(data.image != 'no-image.png')
product.image = uploadDirectory + data._id + '.jpg';
else
product.image = 'assets/images/no-image.png';
product.stock = this._computeStock(data.inStock);
products.push(product);
})
resolve(products);
}, (error) => {
console.log('Erreur lors de la récupération des produits dans la zone : ' + area);
});
});
and...
private _computeStock(inStock:any){
let averagePrice: number = 0;
let totalStock: number = 0;
let lastPurchase: any = null;
let lastOutDate: any = null;
let totalValue: number = 0;
inStock.forEach((stock) => {
averagePrice += parseFloat(stock.totalPrice) / parseInt(stock.initialQuantity);
totalStock += parseInt(stock.initialQuantity);
lastPurchase = moment(stock.purchaseDate).format('DD-MM-YYYY');
let out = stock.out;
if(out.length){
totalStock -= out.quantity;
}
});
totalValue = totalStock * (averagePrice / inStock.length);
return {'totalStock': totalStock, 'lastPurchaseDate': lastPurchase, 'lastOutDate': lastOutDate, 'totalValue': totalValue};
}
Datas are correctly retrieved, but when i want to display them in a view, i got this kind of screen :
The view code is :
<ion-content>
<ion-list inset id="products-by-area">
<ion-item-sliding *ngFor="let product of products">
<ion-item class="item-thumbnail-left item-icon-right item-complex">
<ion-thumbnail item-left>
<img src="{{ product.image }}" title="{{ product.title }}" />
</ion-thumbnail>
<h2>{{ product.title }}</h2>
<ion-note item-end>
{{ product.ean }}
</ion-note>
</ion-item>
<ion-item-options side="right" *ngIf="product.stock.totalStock > 0">
<button ion-button color="warning">
<ion-icon name="remove-circle"></ion-icon>
{{ 'remove' | translate }}
</button>
<button ion-button color="danger" (click)="toTrash(product)";>
<ion-icon name="trash"></ion-icon>
{{ 'trash' | translate }}
</button>
<button ion-button color="success">
<ion-icon name="add-circle"></ion-icon>
{{ 'add' | translate }}
</button>
</ion-item-options>
<ion-item-options side="left">
<button ion-button color="success">
<ion-icon name="stats"></ion-icon>
{{ 'stats' | translate }}
</button>
</ion-item-options>
</ion-item-sliding>
</ion-list>
</ion-content>
Don't understand why product.title or product.image, or even product.ean are not displayed ?
Try to modify type of the public products property, but... nothing appears, as if the product variable was not an object or an empty object.
I'm new to ionic 2 and really don't understand what it's wrong.

Related

How to render element depends on selected option?

i'm newbie in react js , and i want to have a form with select options
i want that when user click on each option , each option render different elements
class Resepy extends Component {
state = {
Resepy : 'default'
}
render() {
return = (
<div className="Resepy">
<form>
<select id="id_field1" name="field1" onChange={(e) => this.state.Resepy = "Burger"}>
<option value="default">Food type not selected</option>
<option value="burger" onClick={(e) => this.setState({ Resepy: 'Burger' })}>Burger</option>
<option value="pizza" onClick={(e) => this.setState({ Resepy: 'Pizza' })}>Pizza</option>
</select>
<div className="food">
{ this.state.Resepy === "burger" ? <div className="burger"></div> //can return any html
: <div className="default">default</div>
}
<div className="pizza"></div>
<div className="food-detail"></div>
</div>
<button type="submit">Add to tray</button>
</form>
</div>
);
}
}
export default Resepy;
General ternary operator used for more readable code.
Like this:
<form>//can be any element
{ codition == true ? <div>It is true</div> //can return any html
: <div>It is false</div>
}
</form>
Tested, working. Problem was with onClick method option cannot invoke that event.
class Resepy extends React.Component {
constructor(props){
super(props);
this.state = {
selected : 'default'
};
}
setSelected = (event) => {
let select = document.getElementById("id_field1");
this.setState({selected: select.value});
//document.getElementById("test").innerHTML = select.value;
}
render() {
return (
<div className="Resepy">
<h1>Something</h1>
<form>
<select id="id_field1" name="field1" onChange={this.setSelected}>
<option value="default">Food type not selected</option>
<option value="burger">Burger</option>
<option value="pizza">Pizza</option>
</select>
<div id="test"></div>
<div className="food">{
(this.state.selected === "default") ?
<div className="default">Default</div>
: (this.state.selected === "burger") ?
<div className="burger">Burger</div>
: <div className="pizza">Pizza</div>
}</div>
<button type="submit">Add to tray</button>
</form>
</div>
);
}
}
I have a hard time understanding you, but the most likely thing you could be trying to achieve with the following code from your original question:
<div className="burger" Resepy={this.state.Resepy === 'burger'}></div>
is:
<div className="food">
<div className={this.state.Resepy} />
</div>
Working example (but I am using Hooks instead of a class component):
const App = () => {
const [selected, setSelected] = React.useState('default')
const handleChange = (event) => {
setSelected(event.target.value)
}
return (
<div>
<select value={selected} onChange={handleChange}>
<option>default</option>
<option>burger</option>
<option>pizza</option>
</select>
<div className="food">
<div className={selected}>{selected}</div>
</div>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
.default { color: gray; }
.burger { color: orange; }
.pizza { color: red; }
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>
Now i want to render html elements depends on values , i tried this but it shows just [Object Object]
setSelected = (event) => {
let select = document.getElementById("id_field1");
document.getElementById("food").innerHTML =
select.value == "default" ?
<div className="default">Default</div>
: select.value == "Burger" ?
<div className="burger">Burger</div>
: <div className="pizza">Pizza</div>
}

how to load data in select item in ionic 2 and know the selected item?

My current attempt below
page.html
<form (ngSubmit)="InsertLocation()" #registerForm="ngForm">
<ion-row>
<ion-col>
<img src="assets/img/1.jpg" />
<ion-list>
<ion-item>
<ion-label>Chauffeur</ion-label>
<ion-select [(ngModel)]="selectedvalue"name="chauff">
<ion-option *ngFor="let item of chauffeurs"[value]="item.nom_chauffeur">
{{item.nom_chauffeur}}
</ion-option>
</ion-select>
</ion-item>
<ion-list>
<ion-row>
<ion-col>
<button ion-button class="submit-btn" type="submit"
[disabled]="!registerForm.form.valid">Inserer</button>
</form>
page.ts
LoadChauffeurs(id){
this.data.LoadChauffeur().subscribe(
data => {
this.chauffeurs= data;
},
err => {
console.log(err);
},
() => console.log('success!')
);
}
knowing the result of data is an array like this
[{
"id_chauffeur":6,
"nom_chauffeur":"ggg",
"num_tel":2563,"id_chef":10
}]
and my service that i call it data in page.ts
data-service.ts
LoadChauffeur(id) {
var url =
'http://localhost/PFEBACKEND/retrievechauffeurs.php?'key=random&id='+id;
var response = this.http.get(url).map(res => res.json());
return response;
}

PopoverCmp ionViewPreLoad error: No component factory found for SearchJobsPopOverPage

I am in the process of upgrading from Ionic 2 beta to rc3. I have the following components that were working, but there must be something I need to do to make it fit with rc3.
When the user clicks an icon, it invokes the following function inorder to show a popover.
presentPopover(event: Event): void {
this.popover = this.popoverController.create(SearchJobsPopOverPage, {
ev: event
});
this.popover.present();
}
SearchJobsPopOverPage
import { Component } from '#angular/core';
import { NavController, ViewController, NavParams, Events } from 'ionic-angular';
import { MapPage } from '../map/map';
import { CategoryPage } from '../category/category';
import { JobModel } from '../model/jobModel';
import { ReviewPage } from '../review/review';
import { RatingModel } from '../model/ratingModel';
import { PersonModel } from '../model/personModel';
import { DateTimePage } from '../datetime/datetime';
#Component({
//selector: 'searchjobspopover',
template: `
<ion-content padding id="search-popover">
<ion-list>
<ion-row>
<ion-col>
<div style="text-align:center">
<div id="pinButton"><button ion-button class="search-popover-button" (click)="presentFilterMap()" color="danger"><ion-icon class="search-popover-icon" name="pin"></ion-icon></button></div>
<p>Location</p>
</div>
</ion-col>
<ion-col>
<div style="text-align:center">
<div id="pinButton"><button ion-button class="search-popover-button" (click)="presentFilterCategories()" primary><ion-icon class="search-popover-icon" name="happy"></ion-icon></button></div>
<p>Sectors</p>
</div>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<div style="text-align:center">
<div id="pinButton"><button ion-button class="search-popover-button search-button-star" (click)="presentFilterRating()"><ion-icon class="search-popover-icon" name="star"></ion-icon></button></div>
<p>Rating</p>
</div>
</ion-col>
<ion-col>
<div style="text-align:center">
<div id="pinButton"><button ion-button class="search-popover-button" (click)="presentFilterTime()" color="secondary"><ion-icon class="search-popover-icon" name="time"></ion-icon></button></div>
<p>Last Online</p>
</div>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<div style="text-align:center">
<div id="pinButton"><button ion-button class="search-popover-button" (click)="clearFilters()" color="light"><ion-icon class="search-popover-icon" name="trash"></ion-icon></button></div>
<p>Clear Filters</p>
</div>
</ion-col>
</ion-row>
</ion-list>
</ion-content>
`
})
export class SearchJobsPopOverPage {
public nav: NavController = null;
public jobModel: JobModel = null;
public events: Events = null;
public ratingModel: RatingModel = null;
public personModelLoggedIn: PersonModel = null;
public lastOnline: number = null;
constructor(public navParams: NavParams, nav: NavController, public viewCtrl: ViewController, events: Events) {
this.events = events;
this.nav = nav;
this.jobModel = navParams.get('jobModel');
this.lastOnline = navParams.get('lastOnline');
this.personModelLoggedIn = navParams.get('personModelLoggedIn');
if (!this.jobModel) {
this.jobModel = new JobModel();
}
this.ratingModel = navParams.get('ratingModel');
}
presentFilterMap(event: Event) {
//this.viewCtrl.dismiss().then(() => {
this.nav.push(MapPage, {
jobModel: this.jobModel,
ratingModel: this.ratingModel,
fromSearch: true
});
//});
}
presentFilterCategories(event: Event) {
this.viewCtrl.dismiss().then(() => {
this.nav.push(CategoryPage, {
jobModel: this.jobModel,
ratingModel: this.ratingModel,
fromSearch: true
});
});
}
presentFilterRating(event: Event) {
//this.viewCtrl.dismiss().then(() => {
this.nav.push(ReviewPage, {
jobModel: this.jobModel,
ratingModel: this.ratingModel,
personModelLoggedIn: this.personModelLoggedIn,
fromFilter: true
});
//});
}
presentFilterTime(event: Event) {
this.viewCtrl.dismiss().then(() => {
this.nav.push(DateTimePage, {
lastOnline: this.lastOnline,
fromSearch: true
});
});
}
clearFilters() {
if (this.jobModel) {
this.jobModel.locations = [];
this.jobModel.categories = [];
this.jobModel.subCategories = [];
this.lastOnline = null;
}
if (this.ratingModel) {
this.ratingModel.rating = -1;
}
let data = {
jobModel: this.jobModel,
ratingModel: this.ratingModel,
fromClearFilters: true
};
this.nav.popToRoot().then(() => {
this.events.publish('popupFilter:update', data);
});
}
}
Error
The popover is not displayed, but the following error is displayed in the browser console:
PopoverCmp ionViewPreLoad error: No component factory found for SearchJobsPopOverPage
Any help appreciated.
Sill me, I forgot to define the page in app.module.ts as is required post rc0.

I can't use my functions that i created in my .ts

hi I'am new in ionic and i working with ionic 2. my problem is :
I have write the functions in my about.ts this function run well (i have test this in the constructor of the page) but when i call this in about.html, nothing of this functions run. (sorry i don't speak english well)
that is my about.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Contacts, Contact} from 'ionic-native';
import { AlertController } from 'ionic-angular';
//, ContactField
#Component({
selector: 'page-about',
templateUrl: 'about.html'
})
export class AboutPage {
private customColor:string[] = ["#f44336", "#3f51b5", "#2196f3", "#009688", "#4caf50"];
// index qui nous permet de changer de couleur
private indexColor:number = 0;
// les contactes trouvés
public allContacts:Contact[];
public findItem:string;
constructor(public navCtrl: NavController,public alertCtrl: AlertController) {
this.findContact('');
this.openModal();
}
/** Suppression d'un contact */
public delete(contactToDelete:Contact):void{
contactToDelete.remove().then(()=>this.findContact(''));
}
public getCustomColor():string{
let color:string = this.customColor[this.indexColor];
this.indexColor++;
if(this.indexColor === 5){
this.indexColor = 0;
}
return color;
}
/** Ouverture de la modale pour la création de contact */
public openModal():void{
//let modal = Modal.create(CreateContact);
// this._navController.present(modal);
// modal.onDismiss(data => {
// this.allContacts.push(data);
// });
let alert = this.alertCtrl.create({
title: 'soty',
subTitle: 'rost',
buttons: ['OK']
});
alert.present();
}
/** Méthode pour effectuer la recherche de contact */
public findContact(value:any){
let alert = this.alertCtrl.create({
title: value,
subTitle: value,
buttons: ['OK']
});
alert.present();
let fn = value === undefined ? '' :value;
Contacts.find(['displayName', 'phoneNumbers'], {
filter:fn,
hasPhoneNumber:true
}).then(data => {
this.allContacts = data;
});
}
/** Création des initiales sur 2 lettres */
public getCustomInitial(value):string{
let names:string[] = value.split(' ');
let firstName = '';
let secondName = '';
if(names[0] != undefined){
firstName = names[0].substring(0,1);
}
if(names[1] != undefined){
secondName = names[1].substring(0,1);
}
return firstName + secondName;
}
}
that is my about.html
<ion-header>
<ion-navbar>
<ion-title>
Gestion des contacts
</ion-title>
<ion-buttons start>
<button (click)="openModal()">
<ion-icon ios="ios-add" md="md-add"></ion-icon>
</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content padding class="page1">
<ion-item>
<ion-input
type="text"
placeholder="rechercher"
[(ngModel)]="findItem"
(Change)="findContact($event)"></ion-input>
</ion-item>
<ion-list>
<ion-item-sliding *ngFor="let contact of allContacts">
<ion-item class="bloc-contact">
<ion-avatar item-left>
<span
class="initial" [style.background] = "getCustomColor()">
{{ getCustomInitial(contact.displayName) }}
</span>
</ion-avatar>
<h2>{{contact.displayName}}</h2>
<div *ngFor="let phone of contact.phoneNumbers">
<ion-item *ngIf="phone.type == 'mobile'" class="line">
<ion-icon ios="ios-phone-portrait" md="md-phone-portrait"></ion-icon>
Mobile
<ion-badge teal item-right>{{phone.value}}</ion-badge>
</ion-item>
<ion-item *ngIf="phone.type == 'home'" class="line">
<ion-icon ios="ios-home" md="md-home"></ion-icon>
Home
<ion-badge green item-right>{{phone.value}}</ion-badge>
</ion-item>
</div>
</ion-item>
<ion-item-options>
<button danger (click) = "delete(contact)">
<ion-icon name="trash"></ion-icon>
Delete
</button>
</ion-item-options>
</ion-item-sliding>
</ion-list>
</ion-content>
somebody can help me please
there is no problem with openModal() and the way you call it; but you must use this for your input event:
<ion-input type="text" placeholder="rechercher" [(ngModel)]="findItem" (input)='findContact($event.target.value)'>

iOnic list not refreshing after adding a new item to the list using web service

We have a iOnic based project and during check out users can add new address to their account.
This is what my controller file look like
$scope.addAddress = function() {
$scope.showLoading();
addressService.addUserAddress($scope.userDetails.userID, $scope.addAddressdata.houseNo, $scope.addAddressdata.street, $scope.addAddressdata.AddDesc, $scope.addAddressdata.LID)
.success(function(response) {
console.log(response);
$scope.hideLoading();
$scope.closeModal();
$scope.getAllAddress();
});
};
$scope.getAllAddress = function() {
addressService.getAllLocations()
.success(function(response) {
$scope.locations = response;
$scope.hideLoading();
});
};
And this is what my services file look like
function() {
"use strict";
var myApp = angular.module('jobolo');
myApp.service('addressService', ['$http', 'appVariableService', function($http, appVariableService) {
var addressService = this;
addressService.getAllLocations = function() {
var data = {
appid: appVariableService.get('appId')
};
return $http.post(appVariableService.get('baseURL') + 'useraddress/getMyLocation', data);
};
addressService.getUserAddress = function(userId) {
return $http.get(appVariableService.get('baseURL') + 'useraddress/myaddress/' + userId, {cache:false});
};
addressService.addUserAddress = function(userId, houseNo, street, adddesc, lid) {
var data = {
appid: appVariableService.get('appId'),
userid: userId,
houseno: houseNo,
street: street,
adddesc: adddesc,
lid: lid,
};
return $http.post(appVariableService.get('baseURL') + 'useraddress/adAdd' , data);
};
}]);
})();
When I add a new address it does add to the database but isn't showing in list. I tried adding $scope.refreshList(); to the code too. When I log out and come back it does show up. Thank you for your help in advance
View Codes are
<ion-view class="main-content">
<ion-nav-buttons side="secondary">
<button menu-toggle="right" class="button button-icon icon ion-navicon"></button>
</ion-nav-buttons>
<div class="bar bar-subheader">
<h2 class="title">Select Address</h2>
</div>
<ion-content class="has-subheader" scroll="true" overflow-scroll="true" style="bottom:57px">
<div class="list">
<ion-radio
ng-model="data.selectedAddress"
ng-value="address"
ng-repeat="address in userAddresses"
class="radio-nowrap"
>
House No. {{address.HouseNo}}, {{address.Street}}, {{address.AddDesc}}, {{address.AreaName}}, {{address.City}}
</ion-radio>
</div>
<!-- <div class="row">
<div class="col location-form">
<button class="button" type="button" ng-click="openModal()">Add New Address</button>
</div>
</div> -->
</ion-content>
<div class="row" style="position: absolute;bottom: 0;padding:0">
<div class="col location-form">
<button class="button" type="button" ng-click="openModal()">Add New Address</button>
</div>
<div class="col location-form">
<button class="button" type="button" ng-disabled="!data.selectedAddress" ng-click="selectAddress(data.selectedAddress)">Select Address</button>
</div>
</div>