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

Related

Ionic 4 Filter JSON by multiple values

Currently I've been facing an issue when it comes to filtering a local JSON file by multiple criteria. I originally thought this would be a simple fix where you could just club multiple conditions using and(&&). However, whenever the data is loaded to the Ngx-Datatable, nothing is appearing. The filtering has been working with a single condition, which is why I find it really odd that multiple criteria is not working. Could it possibly be an issue with the JSON file? Do I have to use another method to do this? Or is it the way I'm loading the data view? I'm really curious as to why this isn't working as I figured that .filter() could handle the multiple criteria as it has been working with the single condition provided before.
TypeScript File
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import data from './../../assets/pathrequests.json';
import { NavController } from '#ionic/angular';
import { NavigationExtras } from '#angular/router';
import { AlertController } from '#ionic/angular';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Component({
selector: 'app-view-necropsy-details',
templateUrl: './view-necropsy-details.page.html',
styleUrls: ['./view-necropsy-details.page.scss'],
})
export class ViewNecropsyDetailsPage implements OnInit {
pathrequestid: string;
procedureid: string;
requestdate: string;
animalqty: string;
marker: string;
method: string;
fixative: string;
handling: string;
processing: string;
items: any[];
private pathrequests: any[] = data;
tablestyle = 'bootstrap';
constructor(private alertCtrl: AlertController, private http: HttpClient, private route: ActivatedRoute, private router: Router, public navCtrl: NavController) { }
ngOnInit() {
this.route.queryParams.subscribe(params => {
this.pathrequestid = params["pathrequestid"];
this.procedureid = params["procedureid"];
this.requestdate = params["requestdate"];
this.animalqty = params["animalqty"];
this.marker = params["marker"];
this.method = params["method"];
this.fixative = params["fixative"];
this.handling = params["handling"];
this.processing = params["processing"];
});
this.loadData();
}
loadData(){
let data:Observable<any>;
data = this.http.get('assets/tissue.json');
data.subscribe(data => {
this.items = data.filter(item => item.pathrequestid === this.pathrequestid && item.procedureid === this.procedureid);
console.log(this.items);
})
}
}
HTML Template
<ion-header>
<ion-toolbar color="primary">
<ion-buttons slot="start">
<ion-menu-button menu ="main-menu"></ion-menu-button>
</ion-buttons>
<ion-buttons>
<ion-back-button defaultHref="/view-procedure"></ion-back-button>
</ion-buttons>
<ion-buttons class="button_style" slot="end">
<ion-button (click)="switchStyle()">
{{ tablestyle }}
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<ngx-datatable class="necropsydetails_table"
[ngClass]="tablestyle"
[rows]="items"
[columnMode]="'force'"
[headerHeight]="60"
[rowHeight]="'auto'">
<ngx-datatable-column name="tissue"></ngx-datatable-column>
<ngx-datatable-column name="collectflg"></ngx-datatable-column>
<ngx-datatable-column name="weighflg"></ngx-datatable-column>
<ngx-datatable-column name="photoflg"></ngx-datatable-column>
<ngx-datatable-column name="tissuecomment"></ngx-datatable-column>
</ngx-datatable>
</ion-content>
We may rule out the filter as it works. Please post the template as well to aid other viewers.
Given the info available, it may be with the model or template; sometimes needing poking the framework to forcibly render (i.e. Change detection in Angular). I could suggest:
Delaying showing the results view until items is assigned.
Moving the filter inside a pipe and use the async pipe to display the already-filtered data. Items would need to be an Observable though.
this.http.get('assets/tissue.json')
.pipe(filter(item => /*criteria here*/)
then on the template
*ngFor="let item of items | async"
Hope these help.
Your filter should work, but you may have a race condition, or bad parameters. this.procedureid is set in the queryParams async call, but load data is called synchronously but also calls an async function (the http get).
If you move the call to this.loadData() inside the subscribe, that should make sure the data.
ngOnInit() {
this.route.queryParams.subscribe(params => {
this.pathrequestid = params["pathrequestid"];
this.procedureid = params["procedureid"];
this.requestdate = params["requestdate"];
this.animalqty = params["animalqty"];
this.marker = params["marker"];
this.method = params["method"];
this.fixative = params["fixative"];
this.handling = params["handling"];
this.processing = params["processing"];
// calling it now will at least make sure you attempted to set the data from params, but double check the params are actually returning data as well.
this.loadData();
});
// calling it here will execute before the above code
// this.loadData();
}
You can get more sophisticated with other RxJS operators, but this is a simple enough case it may not be worth complicating it just yet.

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>

Ionic API data fetch blank screen

I have been attempting to write my own api's then populate my ionic app with the data. I tested the API's and was getting a CORS error when attempting to call the API. I have since added a proxy to the ionic.config.json file to get around this issue and call the API's. The ionic app no longer crashes, but it now just shows a blank page. Below is my code:
all-patients.ts:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { RestService } from '../../providers/rest-service/rest-service';
#Component({
selector: 'page-all-patients',
templateUrl: 'all-patients.html',
providers: [RestService]
})
export class AllPatientsPage {
public data: any;
constructor(public navCtrl: NavController, public restService: RestService){
this.loadPeople();
}
loadPeople(){
this.restService.load()
.then(data => {
this.data = data;
});
}
}
rest-service.ts:
import { Http } from '#angular/http';
import { Injectable } from '#angular/core';
import 'rxjs/add/operator/map';
/*
Generated class for the RestServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class RestService {
constructor(public http: Http) {
console.log('Hello RestServiceProvider Provider');
}
load() {
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
this.http.get('/api')
.map(res => res.json())
.subscribe(data => {
this.data = data.results;
resolve(this.data);
});
});
}
}
all-patients.html:
<ion-navbar *navbar>
<ion-title>
All Patient Data
</ion-title>
</ion-navbar>
<ion-content class="all-patients">
<ion-list>
<ion-item *ngFor="let item of data">
<h2>{{item.firstName}} {{item.lastName}}</h2>
</ion-item>
</ion-list>
</ion-content>
I am not sure what is causing this issue, but my best guess is there is some sort of issue with the data call in the html, but even the ionic navigation bar from the html code isn't running so I am unsure.
I can see few issues in your code :
1- In your template, you are referencing data but data is undefined at first.
you need to protect your *ngFor with an *ngIf like so :
<ion-content class="all-patients">
<ion-list *ngIf="data">
<ion-item *ngFor="let item of data">
<h2>{{item.firstName}} {{item.lastName}}</h2>
</ion-item>
</ion-list>
<div *ngIf="!data" >Loading data...</div>
</ion-content>
2- In your Service, you are referencing this.data but you don't seem to have declared data in that class.
3- Add a console.log(data) within loadPeople() success to make sure you are receiving a result
4- Finally if you are still receiving a blank page, it's most likely because your CSS is making the page look blank. Inspect your html and see if the content is actually there but not visible due to a missing css class

Password reset: First argument "email" must be a valid string

I'm trying send a password reset link to users' email and receiving the error as in the title of this question.
Here's my resetpassword.ts file
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireAuth } from "angularfire2/auth";
import { User } from "../../models/user";
/**
* Generated class for the ResetpasswordPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-resetpassword',
templateUrl: 'resetpassword.html',
providers: [AngularFireAuth]
})
export class ResetpasswordPage {
resetMsg: string="Reset"
user = {} as User
constructor(private afauth: AngularFireAuth, public navCtrl:
NavController, public navParams: NavParams) {
}
async reset(user: User) {
try{
const result =
this.afauth.auth.sendPasswordResetEmail(this.user.email);
if(result) {
console.log(result);
}
}
catch(e) {
console.error(e);
}
}
}
Here's the code in user.ts file in models folder:
export interface User {
email: string;
password: string;
}
This code below is the part of the html file:
<ion-item>
<ion-label color="primary" floating>Email</ion-label>
<ion-input type="email" [(ngModel)]="user.email"></ion-input>
</ion-item>
<button class="reset" (click)="reset(user)" ion-button round medium icon-end color="primary">
{{ resetMsg }}
<ion-icon name="arrow-forward"></ion-icon>
</button>
Creating the user, login is all good but unable to send the reset password email. Please help! Thanks.
Don't know the underlying issue. But it took me to compile the code again and running the ionic serve command in a new instance to get the issue fixed. #camden_kid your answer helped me to confirm if the email is actually taken as string or not. Thanks!!!

Share data between components using Service - IONIC 2, Angular 2

Is there any way to send data {{error.value}} to another page using a method?
This is my code
<ion-row *ngFor="let errors of adp_principal_menuRS">
<ion-col class="info-col" col-4>
<button ion-button color="primary" small (click)="goToErrors(errors.event)">
{{errors.event}}
</button>
</ion-col>
</ion-row>
goToErrors(menu: string){
console.log(menu);
this.navCtrl.push(AdpDetailPage, {
});
}
I want to send the {{errors.event}} value to another page in the goToErrors() method.
Thanks!
EDIT: I just achieve what I want. I edited the code
Data can be shared using BehaviorSubject between components via service.
Here is an example:
// service.ts
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class ShareService {
private errorSource = new BehaviorSubject<any>(null);
error$ = this.errorSource.asObservable();
setError(error: any){
this.errorSource.next(error);
}
Set the error event in parent component using setError method and subscribe the error in error component.
// error component.ts
constructor(share: ShareService) {
share.error$.subscribe(Err => this.error = Err);
Why don't you send the value using a navParam?
goToErrors(menu: string){
console.log(menu);
this.navCtrl.push(AdpDetailPage, {
errorEvent: menu // <------------------------- Add this line
});
}
And in your AdpDetailPage:
export class AdpDetailPage{
constructor(public navParams: NavParams){
errorEvent = this.navParams.get('errorEvent');
console.log("errorEvent= ", errorEvent);
}
}
Use event emittor.
//Home component.ts import { Events } from 'ionic-angular'; constructor(public events: Events) {} directioChange(user) {this.events.publish('directiochanged', 'true');} //App.component.ts constructor(public events: Events) { events.subscribe('directiochanged', (direction) => { this.isRtl = direction;console.log(direction);});}
I generated a Plunker that hopefully matches with what you are trying to do.
https://plnkr.co/edit/MNqpIqJjp5FN30bJd0RB?p=preview
Service
import { Injectable } from '#angular/core';
#Injectable()
export class ErrorService {
errorInfo: string;
}
Component
#Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<button (click)="goToErrors()">{{errors.event}} </button>
<router-outlet></router-outlet>
</div>
`,
})
export class App {
name:string;
errors = { event: 'Test Error', otherInfo: 'Test Info' };
constructor(private errorService: ErrorService, private router: Router) {
this.name = `Angular! v${VERSION.full}`
}
goToErrors(): void {
// Code to navigate to the other component
this.errorService.errorInfo = this.errors.event;
this.router.navigate(['/a']);
}
}