Ionic 3 Search Bar with JSON Data - json

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.

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);
}
}
}

ionic 3 angular 5 restapi request not working

I'm trying to get data from a api but I cannot print the values in the app. doesn't read the json correctly. not sure what I did wrong..any help for would be helpful. I need to be able to parse down in the json to get the strat_name
this is my code
home.ts:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { RestApiProvider } from '../../providers/restapi/restapi';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
names: string[];
errorMessage: string;
descending: boolean = false;
order: number;
column: string = 'name';
constructor(public navCtrl: NavController, public rest: RestApiProvider) { }
ionViewDidLoad() {
this.getNames();
}
getNames() {
this.rest.getNames()
.subscribe(
names => this.names = names,
error => this.errorMessage = <any>error
);
}
sort() {
this.descending = !this.descending;
this.order = this.descending ? 1 : -1;
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Name List
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-searchbar [(ngModel)]="terms"></ion-searchbar>
<button ion-button type="button" (click)="sort()">Sort</button>
<h1>{{names | json}}</h1>
<ion-item *ngFor="let c of names | search : terms | sort: {property: column, order: order}">
<h2>{{c.strat_name}}</h2>
</ion-item>
</ion-content>
restapi:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { map, catchError } from 'rxjs/operators';
#Injectable()
export class RestApiProvider {
private apiUrl = 'https://macrostrat.org/api/v2/defs/strat_names?all';
constructor(public http: HttpClient) {
console.log(this.apiUrl);
}
getNames(): Observable<string[]> {
return this.http.get(this.apiUrl).pipe(
map(this.extractData),
catchError(this.handleError)
);
}
private extractData(res: Response) {
let body = res;
return body || {};
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const err = error || '';
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
not sure what I did wrong..any help for would be helpful. I need to be able to parse down in the json to get the strat_names.
first, it loads the json
once I click on search
There are multiple issue in your code
1.Your data is coming like { success : { data : array} } so to access data you need to do below
private extractData(res: any) {
if (res && res.success && res.success.data) {
return res.success.data;
}
return [];
}
2.In your html you need to access the properties like this
<ion-item *ngFor="let n of names">
<h2>{{n?.strat_name}}</h2>
</ion-item>
3.Your data is too much and cause a lot of delays to show the data
After all of that fixes it will look like below
https://stackblitz.com/edit/ionic-jb6ni9

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

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>

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