Error While Trying to Display Value from Jsonobject in ionic 3? - json

Hello guys this may be dumb question but am new for ionic development , am facing problem while trying to display values from jsonobject,now let me explain in detail am fetching jsonobject from webservice and need to display it and i have successfully fetched the value from service but couldn't be able to display it while am trying am getting Cannot ready property 'StatusName 'undefined now let me post what i have tried so far :
This is my json getting from service:
{
"StatusName": "Open",
"ApprovalStatusName": "Awaiting Approval",
"CreatedByName": "Mark (Marx)",
"LastModifiedByName": "Mark (Marx)",
"ContractID": 20,
"ContractCode": "PIL",
}
And this is the typescript page:
export class ContractApprovalViewPage {
private contracts :any;
private contracttype:any;
private results:any;
constructor(public navCtrl: NavController, public navParams: NavParams,public contractApprovalViewService:ContractApprovalViewService ) {
this.contracts=this.navParams.get('result');
this.getContractApprovalView(this.contracts);
}
getContractApprovalView(contracttype){
this.contractApprovalViewService.getContractApproval(contracttype).then(data => {
//console.log(data);
this.results=data;
console.log(this.results);
console.log(this.results.CustomerName);
});
}
}
This is my service Page:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Events } from 'ionic-angular';
import 'rxjs/add/operator/map';
#Injectable()
export class ContractApprovalViewService {
private _result;
constructor(public http: Http, public events: Events) { }
getContractApproval(contracttype:any) {
return new Promise(resolve => {
this.http.get('http://172.16.6.187/sf/api/cnrt/getContractapprovalview/'+ contracttype.Column0 +'/C').subscribe(
data => {
// console.log('http://xxxx/xx/xx/'+ contracttype.Column0 +'/C');
this._result = data;
resolve(JSON.parse(this._result._body));
},
err => {
this._result = err;
// this.events.publish("message:error", JSON.parse(this._result._body));
}
);
});
}
}
This is my html Page:
<ion-header>
<ion-navbar>
<ion-title>Approval</ion-title>
</ion-navbar>
</ion-header>
<ion-content >
<ion-list no-padding>
<ion-card>
<ion-item >
{{results.StatusName}}
</ion-item>
</ion-card>
</ion-list>
</ion-content>
Don't know where am making mistake how someone teach me where am wrong, Thanks in advance !

First declare variable above constructor
statusName:string;
then in below function
getContractApprovalView(contracttype){
this.contractApprovalViewService.getContractApproval(contracttype).then(data => {
//console.log(data);
this.results=data;
console.log(this.results);
this.statusName = this.results.statusName;
//this.results.statusName status name key should match the response you are getting.
console.log(this.results.CustomerName);
});
}
}
now in html
just print status name
as you are not passing array so dont use results.statusname
<ion-content >
<ion-list no-padding>
<ion-card>
<ion-item >
{{statusName}}
</ion-item>
</ion-card>
</ion-list>
</ion-content>

Related

SyntaxError: Unexpected token < in JSON at position 1 ionic

How can I solve this problem? Could you please help me. Thank you.
I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn't seem to be the case here.
More confusingly, I rolled the code back to an earlier, known-working version and I'm still getting the error.
error message;
SyntaxError: Unexpected token < in JSON at position 1
at JSON.parse (<anonymous>)
at Response.Body.json (http://localhost:8100/build/vendor.js:67304:25)
at SafeSubscriber._next (http://localhost:8100/build/main.js:358:29)
at SafeSubscriber.__tryOrUnsub (http://localhost:8100/build/vendor.js:32821:16)
at SafeSubscriber.next (http://localhost:8100/build/vendor.js:32768:22)
at Subscriber._next (http://localhost:8100/build/vendor.js:32708:26)
at Subscriber.next (http://localhost:8100/build/vendor.js:32672:18)
at XMLHttpRequest.onLoad (http://localhost:8100/build/vendor.js:67797:38)
at t.invokeTask (http://localhost:8100/build/polyfills.js:3:15660)
at Object.onInvokeTask (http://localhost:8100/build/vendor.js:4973:33)
providers/auth-service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
let apiUrl = "http://localhost/PHP-Slim-Restful/api/";
#Injectable()
export class AuthServiceProvider {
constructor(public http: Http) {
console.log('Hello AuthService Provider');
}
postData(credentials, type){
return new Promise((resolve, reject) =>{
let headers = new Headers();
this.http.post(apiUrl+type, JSON.stringify(credentials), {headers: headers}).
subscribe(res =>{
resolve(res.json());
}, (err) =>{
reject(err);
});
});
}
}
signup.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { TabsPage } from '../tabs/tabs';
import { LoginPage } from '../login/login';
import { AuthServiceProvider } from '../../providers/auth-service/auth-service';
import 'rxjs/add/operator/map';
#IonicPage()
#Component({
selector: 'page-signup',
templateUrl: 'signup.html',
})
export class SignupPage {
responseData: any;
userData = { "username": "", "password": "", "email": "", "name": "" };
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public authService: AuthServiceProvider) {
}
ionViewDidLoad() {
}
signup() {
//api connections
this.authService.postData(this.userData, "signup")
.then((result) => {
this.responseData = result;
console.log(this.responseData);
localStorage.setItem('userData', JSON.stringify(this.responseData))
this.navCtrl.push(TabsPage);
}, (err) => {
//connection failed message
});
}
login() {
this.navCtrl.push(LoginPage);
}
}
signup html
<!--
Generated template for the SignupPage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>Kayıt OL</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<ion-label floating>Adınız</ion-label>
<ion-input type="text" [(ngModel)]="userData.name"></ion-input>
</ion-item>
<ion-item>
<ion-label floating>Mail Adresiniz</ion-label>
<ion-input type="text" [(ngModel)]="userData.email"></ion-input>
</ion-item>
<ion-item>
<ion-label floating>Kullanıcı Adı</ion-label>
<ion-input type="text" [(ngModel)]="userData.username"></ion-input>
</ion-item>
<ion-item>
<ion-label floating>Şifre</ion-label>
<ion-input type="password" [(ngModel)]="userData.password"></ion-input>
</ion-item>
</ion-list>
<div padding>
<button ion-button block (click)="signup()">Üye Ol</button>
Login Page
</div>
</ion-content>
100% This error is due to wrong response from api please check your api response into logs
From api folder, in index.php, juste delete or comment this line "echo $email_check.'<br/>'.$email;" at 83 position
and this line "echo ' Here'; " at 87 position
justification:
A Second parameter of localStorage.setItem in signup.ts file MUST BE A JSON FORMAT
But the api send
"<br/>email#gmail.comhere{"userData": {"user_id":"4","name":"My Name here",
"email":email#gmail.com","username":"myusernamehere",
"token":"c0045c0d75e48f62919b1c0d16461af854049615df2c0d9a7bd755e9679e662a"}}"
And this is not a json format
It work fine for me

Show specific data for the clicked element using popover

when I retrieve data from a json file, in the *ngFor displays all the values in the popover, but I need a specific popover to display based only on the data for selected/clicked weapon. Here is my code any help would be greatly appreciated. Thank you again for your help
Home
import { Component } from '#angular/core';
import { NavController, ViewController, PopoverController, Events} from 'ionic-angular';
import { RestProvider } from './../../providers/rest/rest';
import { PopupPage } from './../../pages/popup/popup';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
weapons: any;
errorMessage: string;
constructor(public navCtrl: NavController, public rest: RestProvider,
public popoverCtrl: PopoverController) {
}
ionViewDidLoad() {
this.getweapons();
}
getweapons() {
this.rest.getweapons()
.subscribe(
weapons => this.weapons = weapons,
error => this.errorMessage = <any>error);
}
presentPopover(myEvent)
{
let popover = this.popoverCtrl.create(PopupPage);
popover.present({
ev: myEvent
});
}
}
home.html
<ion-content>
<ion-searchbar [(ngModel)]="terms"></ion-searchbar>
<ion-item>
</ion-item>
<ion-list>
<button ion-item (click)="presentPopover($event)">
<ion-item *ngFor="let c of weapons?.weapon_category?.weapons | search : terms">
<h2>{{c.name}}</h2>
</ion-item>
</button>
</ion-list>
</ion-content>
popup.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, ViewController, Events} from 'ionic-angular';
import { RestProvider } from './../../providers/rest/rest';
import { HomePage } from './../../pages/home/home';
/**
* Generated class for the PopupPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-popup',
templateUrl: 'popup.html',
})
export class PopupPage {
rangeSettings = 20;
weapons: any;
errorMessage: string;
constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public rest: RestProvider) {
alert('inside the popup');
}
close() {
this.viewCtrl.dismiss();
}
getweapons() {
this.rest.getweapons()
.subscribe(
weapons => this.weapons = weapons,
error => this.errorMessage = <any>error);
}
ionViewDidLoad() {
this.getweapons();
}
}
popup.html
<ion-header>
<ion-navbar>
<ion-title>popup</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item *ngFor="let c of weapons?.weapon_category?.weapons">
<h2>{{c.damage.base}}</h2>
<h2>{{c.damage.chest0}}</h2>
<h2>{{c.damage.chest1}}</h2>
<h2>{{c.damage.chest2}}</h2>
<h2>{{c.damage.chest3}}</h2>
<h2>{{c.damage.head1}}</h2>
<h2>{{c.damage.head2}}</h2>
<h2>{{c.damage.head3}}</h2>
</ion-item>
<ion-item>
<ion-range min="0" max="80" [(ngModel)]="rangeSettings" color="danger" pin="true" snaps="true" disabled=true></ion-range>
</ion-item>
</ion-list>
</ion-content>
Popover doesn't need to hit the REST call again. You can pass the chosen weapon to the popover as a parameter.
Change your function to accept a weapon (make sure you change the code in the HTML too)
presentPopover(myEvent, weapon)
And send it to the popover controller this way:
this.popoverCtrl.create(PopupPage, weapon);
Now in your popup.ts, decleare a weapon object in your class,
weapon : any;
and grab the weapon from the navParams in your constructor
this.weapon = this.navParams.data;
Change your <ion-item> in popup.html to display the selected one.
<ion-item>
{{weapon.damage.base}}
...
</ion-item>

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

Ionic 2 will not let me loop over an object of objects using *ngFor

I am developing an app where users can search for classified ads.
However, I am unable to display the search results.
Here is my search_results.ts:
import {Component} from '#angular/core';
import {NavController, NavParams} from 'ionic-angular';
import {Http} from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'page-page1',
templateUrl: 'search_results.html' })
export class SearchResults {
public term: any;
public ads: any;
public tmp: any;
constructor(public navCtrl: NavController, public params: NavParams, public http: Http) {
this.term = this.params.get('term');
this.ads = [];
this.tmp = [];
console.log("this.term", this.term);
this.http.get('http://www.truckers.host/app/search-ads.php')
.map(res => res.json()).subscribe(data => {
console.log("this is returned from http.get", data);
});
}
ngOnInit() {
// Let's navigate from TabsPage to Page1
console.log(this.params);
} }
Now, in my search_results.html to display the search results, I am not getting anything to print.
Here is that code:
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>
<img src="assets/images/trucker-to-trucker-logo.png" />
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding class="card-background-page">
<ion-card>
<ion-card-header>
Search Results
</ion-card-header>
<ion-card-content>
Searching for: <b>{{ term }}</b>
</ion-card-content>
</ion-card>
<ion-card>
<ion-list>
<ion-item *ngFor="let ad of ads">
{{ ad.ad_id }}
</ion-item>
</ion-list>
</ion-card>
</ion-content>
Nothing is returned, or iterated over.
When I console.log(data), I get an Object of Objects, and Ionic does not want to loop them.
Please let me know what other information I should include to help.
*ngFor only supports for Array and not Json Object.
You should consider using a custom Pipe to convert Object to Array.
Documentation about Pipe.
#Pipe({name: 'toArray'})
export class ToArrayPipe implements PipeTransform {
transform(inputObj: any, arg: any) {
if (!inputObj) { return [] }
let arr = [];
for(let key in inputObj) {
// Option1 (only value without the json object's key)
// this way will lose the key of Json Object
//arr.push(inputObj[key]);
// OPtion2 (both the key and value)
let obj = {};
obj[key] = inputObj[key];
arr.push(obj);
}
return arr;
}
}
Then add it to declarations of NgModule, and use it in your temple this way:
<ion-item *ngFor="let ad of ads | ToArray">
...
</ion-item>

how to use ion-toggle in notification using ionic2

I am doing notifications in ionic 2 i have taken one toggle button and wrote the get and post call for that one.
below is my html code.
<ion-header>
<ion-navbar>
<ion-title>Notifications</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-item no-lines (click)="Update()">
<ion-label> Notification</ion-label>
<ion-toggle checked={{notify}} ></ion-toggle>
</ion-item>
</ion-content>
below is my ts file..
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Logger } from '../../providers/logger/logger';
import { Rest } from '../../providers/network/rest';
/*
Generated class for the Notifications page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
selector: 'page-notifications',
templateUrl: 'notifications.html'
})
export class NotificationsPage {
public noteValue;
public notify : boolean;
NotificationsArray=[];
constructor(public navCtrl: NavController,
public logger: Logger,
public rest: Rest){
}
ionViewDidLoad() {
this.rest.get('/getNotification')
.subscribe((result)=>
{
console.log("checking getNotification"+JSON.stringify(result));
//this.logger.debug(["getNotification"][0]["newsletter"]);
if(result.status == '1'){
if(result.notify == '1'){
this.notify=true;
console.log("success of getNotification");
//this.NotificationsArray=result.data;
}
else{
this.notify=false;
console.log("error of getNotification");
}
}
})
}
Update(){
let setNotificationObj = {
newsletter:this.notify
}
this.notify = !this.notify;
console.log("cheking setNotificationObj " + JSON.stringify(setNotificationObj));
this.rest.post('/setNotification',setNotificationObj)
.subscribe((result)=>
{
console.log("checking data of success " +JSON.stringify(result));
if(result.status == '1'){
}
else{
console.log("error");
}
});
}
}
my get call is working but when i am off&on the toggle button its getting json at position 0 error. please check my post call..