Load Data from mysql to Ionic - mysql

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

Related

Ionic v4 Firebase: cannot read property 'email' of undefined

This code has been bugging me for a good four hours... It's supposed to sign up a user with Firebase's auth system and Ionic 4 components.
Instead it returns the following around a good six times:
ERROR TypeError: Cannot read property 'email' of undefined
Another weird thing is that my code will only nitpick on the property 'email', and won't return errors for having a property 'password'.
signup.page.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
// firebase imports
import * as firebase from 'firebase';
import { AngularFireAuth } from '#angular/fire/auth';
import { ToastController } from '#ionic/angular';
// model import
import { User } from '../../models/login.interface';
#Component({
selector: 'app-signup',
templateUrl: './signup.page.html',
styleUrls: ['./signup.page.scss'],
})
export class SignupPage implements OnInit {
constructor(
private afAuth: AngularFireAuth,
private route: Router,
public toast: ToastController
) { }
ngOnInit() {
}
async signup(user: User) {
console.log('starting auth');
try {
const result = await firebase.auth().createUserWithEmailAndPassword(user.email, user.password);
if (result) {
this.route.navigateByUrl('/add-profile');
}
} catch (e) {
console.log(e);
}
}
}
signup.page.html
<ion-header>
<ion-toolbar>
<ion-title>SIGNUP</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-item>
<ion-label position="stacked">Email</ion-label>
<ion-input type="text" [(ngModel)]="user.email"></ion-input>
</ion-item>
<ion-item>
<ion-label position="stacked">Password (6+ characters)</ion-label>
<ion-input type="password" [(ngModel)]="user.password"></ion-input>
</ion-item>
<ion-fab vertical="bottom" horizontal="end" slot="fixed">
<ion-fab-button (click)="signup(user)">SIGNUP
</ion-fab-button>
</ion-fab>
</ion-content>
user.interface.ts
export interface User {
email: string;
pasword: string;
}
Any help would be appreciated! Thank you!
Create a user and initialize it with empty values either in constructor or ngOnInit like below
user:User;
//inside constructor or ngOnInit
this.user = {
email: '',
pasword: ''
}
// firebase imports
import * as firebase from 'firebase';
import { AngularFireAuth } from '#angular/fire/auth';
import { ToastController } from '#ionic/angular';
// model import
import { User } from '../../models/login.interface';
#Component({
selector: 'app-signup',
templateUrl: './signup.page.html',
styleUrls: ['./signup.page.scss'],
})
export class SignupPage implements OnInit {
user: User = {
email: '',
password: ''
}
constructor(
private afAuth: AngularFireAuth,
private route: Router,
public toast: ToastController
) { }
ngOnInit() {
}
async signup(user: User) {
console.log('starting auth');
try {
const result = await firebase.auth().createUserWithEmailAndPassword(user.email, user.password);
if (result) {
this.route.navigateByUrl('/add-profile');
}
} catch (e) {
console.log(e);
}
}
}

Navigate between ionic pages

I'm fetching data from json data : https://jsonplaceholder.typicode.com/posts and I want to show every post details when click on button in another page to show thoses details : https://jsonplaceholder.typicode.com/posts/3
i created a provider and consuming the data and everything work for the home page, but I got an error when passing the post ID to the method that search the post by id !
provider:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { URLS } from '../urls/postUrls'
#Injectable()
export class PostsProvider {
constructor(public http: HttpClient) {
}
getPosts(){
return new Promise(resolve => {
this.http.get(URLS.POSTS).subscribe(data => {
resolve(data);
}, err =>{
console.log(err);
});
});
}
getPostByID(id){
for (let i = 0; i < this.getPosts.length; i++) {
if (this.getPosts[i].id == id) {
return Promise.resolve(this.getPosts[i]);
}
}
}
}
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { PostsProvider } from '../../providers/posts/posts';
import { PostPage } from '../post/post'
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
posts: any;
constructor(public navCtrl: NavController, public postsProvider: PostsProvider) {
this.getPosts();
}
getPosts() {
this.postsProvider.getPosts()
.then(data => {
this.posts = data;
});
}
postDetails(id){
this.navCtrl.push(PostPage, { id: id });
}
}
home.html
<ion-content >
<ion-card *ngFor="let post of posts">
<img src="https://placekitten.com/760/300"/>
<ion-card-content>
<ion-card-title class="post-title">
{{ post.title }}
</ion-card-title>
<p class="post-content">
{{ post.body | slice:0:80}} ...
</p>
<button ion-button button-small read-more (click)="postDetails(post.id);">Read more</button>
</ion-card-content>
</ion-card>
</ion-content>
post.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { PostsProvider } from '../../providers/posts/posts';
#IonicPage()
#Component({
selector: 'page-post',
templateUrl: 'post.html',
})
export class PostPage {
post: any=0;
constructor(public navCtrl: NavController, public navParams: NavParams, public postsProvider: PostsProvider) {
this.postsProvider.getPostByID(this.navParams.get('id')).then( result => {
this.post = result;
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad PostPage');
}
}
post.html
<ion-content padding *ngIf= "post != 0">
<p>{{ post.title }}</p>
<strong> {{ post.body}} </strong>
I didn't find the right way to pass parameters to get the details page of the post ! can any one check what going on with id parameter ?
I got this error :
ERROR Error: Uncaught (in promise): TypeError: Cannot read property
'id' of undefined
you could pass the hole post object like this
<button ion-button button-small read-more (click)="postDetails(post)">Read more</button>
in home.ts
postDetails(post){
this.navCtrl.push(PostPage, { post: post });
}
then in postPage
constructor(public navCtrl: NavController, public navParams: NavParams, public postsProvider: PostsProvider) {
this.post = this.navParams.get('post');
}
id: any = 0;
constructor(public navCtrl: NavController, public navParams: NavParams, public postsProvider: PostsProvider) {
this.id = this.navParams.get('id')
this.getPostDetails()
}
getPostDetails(){
this.postsProvider.getPostByID(this.id).then( result => {
this.post = result;
});

Uncaught Error: Can't resolve all parameters for MyloginPage

I created a login page which data I want to store to localStorage when passed from php api, but whenever i click on the button to the login page an error always occured.
i have searched through the net for a more details based on this error but I was unable to come up with anything.
Below is the error displayed to my screen when I tried to access my login page:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[MyloginPage -> AuthServiceProvider]:
StaticInjectorError(Platform: core)[MyloginPage -> AuthServiceProvider]:
NullInjectorError: No provider for AuthServiceProvider!
Error: StaticInjectorError(AppModule)[MyloginPage -> AuthServiceProvider]:
Below is the image:
Mylogin.html
<ion-content padding>
<ion-list>
<ion-item>
<ion-label>username</ion-label>
<ion-input type="text" name="username" [(ngModel)]="data.username"></ion-input>
</ion-item>
<ion-item>
<ion-label>password</ion-label>
<ion-input type="password" name="password" [(ngModel)]="data.password"></ion-input>
</ion-item>
</ion-list>
<button ion-button color="primary" full (click)="login()">Login</button>
</ion-content>
**mylogin.ts**
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';
import { AuthServiceProvider } from '../../providers/auth-service/auth-service';
import { Storage } from '#ionic/storage';
/**
* Generated class for the MyloginPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-mylogin',
templateUrl: 'mylogin.html',
})
export class MyloginPage {
data: any;
public local : Storage;
constructor(public navCtrl: NavController, public navParams: NavParams, private viewCtrl: ViewController, private service: AuthServiceProvider) {
this.data = {};
this.data.username = "";
this.data.password = "";
this.local = new Storage(null);
}
ionViewDidLoad() {
console.log('ionViewDidLoad MyloginPage');
}
login() {
let username = this.data.username;
let password = this.data.password;
let data = JSON.stringify({username, password});
this.service.postLogin(data);
}
dismiss(){
this.viewCtrl.dismiss();
}
}
Auth-service.ts
//import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import { Storage } from '#ionic/storage';
/*
Generated class for the AuthServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class AuthServiceProvider {
public local : Storage;
mydata: any;
constructor( public http: Http) {
this.local = new Storage(null)
}
postLogin(data){
let link = "http://textkhmer.com/api/securelogin.php";
return this.http.post(link, data)
.map(data => {
this.mydata = data;
console.log("data")
}, error =>{
console.log(error)
})
}
}
Please why is this error displaying?
Thanks

Firebase Cloud Firestore can not load data

When I open web data is show but I change component and come back this component data not show.It show no item. I check log but not run to ngOnIt. ngOnIt run on web strat or web reload.
this is stock.service.ts
import { Injectable } from '#angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import { Stock } from './stock.model';
#Injectable()
export class StockService {
stocksCollection: AngularFirestoreCollection<Stock>;
stocks: Observable<Stock[]>;
constructor(public afs: AngularFirestore) {
this.stocks = this.afs.collection('stocks').valueChanges();
}
getStock(){
return this.stocks;
}
}
stock.component.ts
import { Component, OnInit, Input } from '#angular/core';
import { ActivatedRoute,Params } from '#angular/router';
import { StockService } from '../shared/stock.service';
import { Stock } from '../shared/stock.model';
import { Brands } from '../shared/brand';
import { Subscription } from 'rxjs/Subscription';
#Component({
selector: 'app-stock',
templateUrl: './stock.component.html',
styleUrls: ['./stock.component.css']
})
export class StockComponent implements OnInit {
stocks: Stock[];
brand: Brands;
sub: Subscription;
brand_name: string;
constructor(
private stockService: StockService,
private router: ActivatedRoute
) { }
ngOnInit() {
this.stockService.getStock().subscribe(stocks => {
console.log(stocks);
this.stocks = stocks;
});
this.sub = this.router.params.subscribe(params =>{
this.brand_name = params['brand'];
});
console.log('Brand : '+this.brand_name);
}
}
and stock.component.html
<div *ngIf="stocks != null || stocks?.length > 0 ; else noStocks" >
<ul *ngFor="let item of stocks" class="collection">
<li class="collection-item " >{{item.name}} | {{item.brand}} | {{item.price}}</li>
</ul>
</div>
<ng-template #noStocks>
<p>no item</p>
</ng-template>
I don't know where code is mistake. Thank you for answer.
Don't load inside the constructor of your service, move it inside your method
constructor(public afs: AngularFirestore) {
}
getStock(){
this.stocks = this.afs.collection('stocks').valueChanges();
return this.stocks;
}

Ionic 3 Search Bar with JSON Data

Somebody please help me. I am trying to filter a JSON data but it does not working and also don't show an error.
i have read the ionic Documentation, but it just work for an array data.
this is my ts file
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
//untuk membaca file json
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
//navigasi ke tampilPage
import { TampilPage } from '../tampil/tampil';
//panggil provider
import { AlQuranProvider } from '../../providers/al-quran/al-quran';
#Component({
selector: 'page-al-quran',
templateUrl: 'al-quran.html',
})
export class AlQuranPage {
searchQuery: string = '';
public alquranTerfilter: string[];
constructor(
private quranProvider: AlQuranProvider,
private http: Http,
public navCtrl: NavController,
public navParams: NavParams) {
}
ionViewDidLoad(){
this.quranInitializeItems();
}
quranInitializeItems(){
this.quranProvider.getQuran().subscribe(
(respon) => {
//this.alquran = respon;
this.alquranTerfilter = respon;
});
}
getItems(ev: any) {
// Reset items back to all of the items
this.quranInitializeItems();
// set val to the value of the searchbar
var val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.alquranTerfilter = this.alquranTerfilter.filter((item) => {
return (item.toString().toLowerCase().indexOf(val.toString().toLowerCase()) > -1);
})
}
}
tampilkan(item){
this.navCtrl.push(TampilPage, {item: item});
}
}
//this.alquran = respon;
/*
if (val && val.trim() != '') {
this.alquranTerfilter = this.alquranTerfilter.filter((item) => {
return (item.toString().toLowerCase().indexOf(val.toString().toLowerCase()) > -1);
})
}
*/
<!--
Generated template for the AlQuranPage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>AlQuran</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
<ion-list>
<ion-item *ngFor="let item of alquranTerfilter" (click)="tampilkan(item)">
<h2>{{item.judul}}</h2>
<h4>{{item.riwayat}}</h4>
<ion-icon name="arrow-forward" item-end></ion-icon>
</ion-item>
</ion-list>
</ion-content>
and this the provider
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the AlQuranProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class AlQuranProvider {
// public alquran: string[];
//public alquranTerfilter: string[];
constructor(public http: HttpClient, private httpnonclient: Http) {
}
getQuran(){
return this.httpnonclient.get('./assets/nash/tbQuran.json')
.map(respon => respon.json());
}
}
the filter doesn't working and doesn't showing any error.
sorry for my bad english.
I guess it's a search function right ? Try this
getItems(ev: any) {
this.quranInitializeItems();
var val = ev.target.value;
if (val && val.trim()) {
this.alquranTerfilter = this.alquranTerfilter.filter(
item => item.toString().toLowerCase().includes(val.toString().toLowerCase())
)
} else {
return [];
}
}
I didn't get your filter logic, and you forgot to return something in case your query is empty.