Access item in JSON array and display objects data - json

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>

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 storage get data and show it in html

i want to show data in html from local storage but i got error [object promise]. i don't know how to show data in html. i can show data from console but cannot show in html. please help me
TS
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Storage } from '#ionic/storage';
import { PengaturanPage } from "../../pengaturan/pengaturan";
#IonicPage()
#Component({
selector: 'page-biodata',
templateUrl: 'biodata.html',
})
export class BiodataPage {
inputnama: string;
public name: any;
constructor(public navCtrl: NavController,
public navParams: NavParams,
private storage: Storage) {`enter code here`
}
saveData(){
this.storage.set('name', this.inputnama);
}
loadData(){
this.storage.get('name').then((name) => {
console.log(name);
});
}
HTML :
<ion-row padding-top>
<ion-col class="col-tengah" col-10 no-padding>
<ion-item style="background: transparent" >
<ion-input class="input-biodata" [(ngModel)]="inputnama" placeholder="Nama">{{name}}</ion-input>
</ion-item>
</ion-col>
</ion-row>
You need to call saveData() and loadData() somewhere of course. I assume, you did this already.
To display the data in your template, you need to store the data in any attribute of your class. In your case you want to store it like this:
this.storage.get('name').then((name) => {
this.name = name;
});
After this Promise (Note: It is asynchronous, that is important to know), your name attribute is populated with any value your stored in LocalStorage before.
You maybe want to use .catch() on the Promise to catch any errors, that occur, when you have not stored any value for name.

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

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.

Display image json object into ionic list ( v2)

I have a json object that contains id of an image and its url in the server , in order to display it in an ion-list i try the code below but the image doesn't appear.
About.html
<ion-content padding>
<ion-list>
<ion-item *ngFor="let post of posts">
<img [src]="post.pic"/>
</ion-item>
</ion-list>
</ion-content>
here is my json object :
{"ListeImages":[{"id":"44","pic":"https:\/\/stationpfe.000webhostapp.com\/projet\/uploads\/1494201248244.jpg"}],"success":1}
About.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Imageservice} from '../../providers/imageservice';
import { Http } from '#angular/http';
#Component({
selector: 'page-about',
templateUrl: 'about.html',
providers:[Imageservice]
})
export class AboutPage {
posts: any;
constructor(public navCtrl: NavController,public im:Imageservice,public http: Http) {
this.getImages();
}
getImages(){
this.im.OneArrive().subscribe(response=>
{
this.posts=response.ListeImages;
});
}
}
imageservice.ts ( provider)
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class Imageservice {
constructor(public http: Http) {
console.log('Hello Imageservice Provider');
}
public OneArrive(){
var url='https://stationpfe.000webhostapp.com/projet/SelectListeImages.php';
return this.http.get(url).map(res=>res.json());
}
}
<ion-avatar item-left>
<img [src]="imageUrl+card.image" />
</ion-avatar>
i have stored the image url in .ts file the card.image value is the value that i get from server.
In my case i have a server storage=>http://311.11.111.111:8000/storage<=like this
i specify the storage + the value from api to display in the
<img [scr]=""/> specified above.
Hope it helps....