Ionic API data fetch blank screen - html

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

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.

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.

How to include the user credentials in every sidebar of very pages in ionic

I want to have an sidebar that can display the name of the user who logged in. I have an account page that display all the details of the user. This is the code of the typescript below for the accounts page.
import { Component } from '#angular/core';
import { NavController, AlertController} from 'ionic-angular';
import {Headers} from "#angular/http";
import 'rxjs/add/operator/map';
import {Storage} from "#ionic/storage";
import { Global } from '../../providers/global';
#Component({
selector: 'page-account',
templateUrl: 'account.html',
})
export class AccountPage {
constructor(public navCtrl: NavController,
private storage: Storage,
public alertCtrl: AlertController,
public global: Global
)
{
//
}
public ACCOUNT_URL = this.global.url + "/api/inspectors";
credentials:any;
contentHeader = new Headers({"Content-Type": "application/json"});
error: any;
user: any;
token_type: any;
access_token: any;
refresh_token:any;
ionViewDidLoad() {
console.log('ionViewDidLoad AccountPage');
this.getAccessToken();
this.getAccount();
}
getAccessToken(){
this.storage.get('access_token').then((value) => {
this.access_token=value;
});
}
getAccount(){
this.storage.get('user').then((value) => {
this.user=value;
});
}
}
and this is the code in my html.
<ion-header>
<ion-navbar color="danger">
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Account</ion-title>
</ion-navbar>
</ion-header>
<ion-content class="page-account">
<ion-card>
<ion-item *ngIf="user">
<ion-card-content text-wrap>
<h2>Name: {{user.name}}</h2>
<p>{{user.cellphone_no}}</p>
<p> Address: {{user.address}} </p>
<p> Email: {{user.email}} </p>
</ion-card-content>
</ion-item>
</ion-card>
</ion-content>
What I want to happen is to delete the account pages and put the details of the user in top of the sidebar. So I have to put it into the app.html or app.ts but how can I define the property in my root component in order to display the details of that user.
Here is the code below in my app.component.ts
import { Component, ViewChild} from '#angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import {Storage} from "#ionic/storage";
import { LoginPage } from '../pages/login/login';
import { AccountPage } from '../pages/account/account';
import { InspectionPage } from '../pages/inspection/inspection';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = LoginPage;
#ViewChild(Nav) nav: Nav;
pages: Array<{title: string, component: any, icon: string, color: string}>;
constructor(platform: Platform,
statusBar: StatusBar,
private storage: Storage,
splashScreen: SplashScreen) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
// used for an example of ngFor and navigation
this.pages = [
//{ title: 'Home', component: HomePage, icon: 'home', color: 'primary' },
{ title: 'Home', component: InspectionPage, icon: 'home', color: 'danger' },
{ title: 'Account', component: AccountPage, icon: 'person', color: 'primary' }
];
}
openPage(page) {
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
this.nav.setRoot(page.component);
}
logout() {
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
this.storage.remove('access_token');
this.storage.remove('username');
this.storage.remove('data');
this.storage.remove('user');
this.nav.setRoot(LoginPage);
}
}
and here is the code in my sidemenu or html.
<ion-menu [content]="content" id="myMenu">
<ion-header>
<ion-toolbar color="danger">
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<button menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)">
<ion-icon [name]="p.icon" [color]="p.color" item-left></ion-icon> {{p.title}}
</button>
<button menuClose ion-item (click)="logout()">
<ion-icon name="log-out" color="default" item-left></ion-icon> Logout
</button>
</ion-list>
</ion-content>
</ion-menu>
<!-- Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
What I want to happen is to put the details of the user in the sidebar like what I did in the account page. Sorry for my long question. I tried searching for it but can't find any answer to it.
Looking for help.
Thanks in advance.
I would recommend that you create a service to handle the state of the user login. That way the state is handled in a central place and it will be much easier to maintain.
One possible approach would be to use a BehaviourSubject inside your service, which you can then subscribe to on every page that you need your user object (like your account page and your app component).
import {Injectable} from '#angular/core'
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
#Injectable()
export class UserService {
// Observable user object (replace any with your user class/interface)
private _userObject = new BehaviorSubject<any>({});
// Expose an observable that can be used by components
userObject$ = this._userObject.asObservable();
// Method to update the user
changeUser(user) {
this._userObject.next(user);
}
}
You can now use the service like that (you have to implement the subscription logic in every component where you want to have access to your user):
import {Component} from '#angular/core';
import {UserService} from './user.service';
#Component({
selector: 'account-page'
})
export class AccountPage {
user: any;
subscription: Subscription;
constructor(private _userService: UserService) {}
ngOnInit() {
this.subscription = this._userService.userObject$
.subscribe(item => this.user = item);
}
ngOnDestroy() {
// prevent memory leak when component is destroyed
this.subscription.unsubscribe();
}
login() {
this._userService.changeUser({
name: 'Name' // Replace with name / user object
});
}
logout() {
this._userService.changeUser({});
}
}
As mentioned above, the big advantage is maintainability. If you ever change your user object, it only requires minimal changes, whereas the solution by #Tomislav Stankovic requires changes in every component where the user is used.
In your login page, when user is successfully logged-in, store data to localStorage
login(username,password){
this._api.userLogin().subscribe(res => {
if(res.status == 'ok'){
localStorage.setItem('user_first_name', res.user_first_name);
localStorage.setItem('user_last_name', res.user_last_name);
}
}
And then in app.component.ts get data from localStorage
this.first_name = localStorage.getItem('user_first_name');
this.last_name = localStorage.getItem('user_last_name');
Display data in app.html
<p>{{first_name}}</p>
<p>{{last_name}}</p>
On log-out clear localStorage
logout(){
localStorage.clear();
}

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

Ionic 2 consuming json issue

I'm using Ionic 2 and i couldn't consume a json. for some reason it throws an error.
Here is my updated code.
sales-service.ts
#Injectable()
export class SalesService {
constructor(public http: Http) {
this.http = http;
}
retrieveSalesData() {
return this.http.get("http://api.randomuser.me/?results=10");
}
}
sale.ts
#Component({
selector: 'page-sale',
templateUrl: 'sale.html',
providers: [SalesService],
})
export class SalePage {
data:any;
constructor(data: SalesService) {
this.data=data.retrieveSalesData().subscribe(data =>{
this.data=JSON.parse(data._body).results;
console.log("Inside Subscribe (All Elements):"+ this.data);
console.log("Inside Subscribe (Single Element):"+this.data[1].name.first);
});
console.log("Inside Constructor (All Elements):"+ this.data);
console.log("Inside Constructor (Single Element):"+ this.data[1].name.first);
}
ionViewDidLoad() {
console.log("Inside IonView (All Elements):"+ this.data);
console.log("Inside IonView (Single Element):"+this.data[1].name.first);
}
}
sale.html -- This is not the issue so i've commented the code
<ion-list>
<ion-content padding>
<!--<ion-list>
<ion-item *ngFor="let item of data">
<h2>{{item.name.first}}</h2>
</ion-item>
</ion-list>-->
</ion-content>
Here is my error:
I think i found the issue, but don't know how to clear it.
All elements are received in subscribe, but not in constructor and as well as in IonView. Please advise.
Here is my ionic info
I don't care of your update1.
I assume you get response object in this.data object.
If you are dealing with latest angular2 version, make sure you use let keyword instead of # as show below,
<ion-item ngFor="let person of data"> //<<<===here
<p>{{person?.name.first}}</p> //<<<=== (?.) operator is used as you deal with async call.
</ion-item>
</ion-list>
change your sales-service.ts file like bleow
#Injectable()
export class SalesService {
salesData:any;
constructor(public http: Http) {
//this.http = http;
this.salesData = [];
}
retrieveSalesData() {
this.http.get('https://randomuser.me/api/?results=10')
.subscribe(salesData => {
this.salesData = salesData.result;
});
}
}
inside your html
<ion-list>
<ion-item *ngFor="let person of data">
<p>{{person.name.first}}</p>
</ion-item>
</ion-list>
</ion-content>
Try the follwoing
sales-service.ts
#Injectable()
export class SalesService {
salesData:any;
constructor(public http: Http) {
this.http = http;
this.salesData = null;
}
retrieveSalesData() {
return this.http.get('https://randomuser.me/api/?results=10')
}
}
sale.ts
#Component({
selector: 'page-sale',
templateUrl: 'sale.html',
providers: [SalesService]
})
export class SalePage {
data:any;
constructor(private salesService: SalesService) {
}
ionViewDidLoad() {
this.salesService.retrieveSalesData()
.subscribe(salesData => {
this.data= salesData;
});
}
}
Try upgrading your app-scripts:
npm install #ionic/app-scripts#latest
Their previous version was missing a JSON plugin which they just added to the rollup process.
I found the answer that's working for me.
This is what i did,
public data:Users[]=[];
constructor(public pdata: SalesService) {
pdata.retrieveSalesData().subscribe(data =>{
JSON.parse(data._body).results.forEach(element => {
this.data.push(
new Users(element.name.first)
);
});
});
}
export class Users {
name: string;
constructor(_name: string) {
this.name = _name;
}
}
This works for me. If there is an alternative and elegant way. please feel free to update the answer. Thank you for all your time.