SyntaxError: Unexpected token < in JSON at position 1 ionic - json

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

Related

JSON error is coming while performing login using API in Ionic

I am performing the login using API in Ionic but I am getting the error :
Error: Property 'json' does not exist on type '{}'.
This is my loginpage.html:
<ion-header>
<ion-navbar>
<ion-title>loginpage</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<form (submit)="getloginUsers()">
<ion-list>
<ion-item>
<ion-label fixed>Email</ion-label>
<ion-input type="email" [(ngModel)]="userData.email" name="email"></ion-input>
</ion-item>
<ion-item>
<ion-label fixed>Password</ion-label>
<ion-input type="password" [(ngModel)]="userData.password" name="password"></ion-input>
</ion-item>
<div padding>
<button ion-button color="primary" block>Login</button>
</div>
</ion-list>
</form>
</ion-content>
This is my loginpage.ts:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { RestapiProvider } from '../../providers/restapi/restapi';
import { ListPage } from '../list/list';
#IonicPage()
#Component({
selector: 'page-loginpage',
templateUrl: 'loginpage.html',
})
export class LoginpagePage {
responseData : any;
userData = {"email": "", "password": ""};
constructor(public navCtrl: NavController, public navParams: NavParams,
public restProvider: RestapiProvider) {
this.getloginUsers();
}
ionViewDidLoad() {
console.log('ionViewDidLoad LoginpagePage');
}
getloginUsers(){
this.restProvider.getUsers(this.userData,'user_Login').then((result) => {
if(result){
this.responseData = result.json();
if(this.responseData.userData){
console.log(this.responseData);
console.log("User Details");
this.navCtrl.push(ListPage);
}
else{
console.log("Incorrect Details"); }
}
}
, (err) => {
// Error log
});
}
}
This is code this.responseData = result.json(); error is coming.
Error: Property 'json' does not exist on type '{}'.
This is my Service restapi.ts:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { HttpHeaders } from '#angular/common/http';
import { Response } from '#angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout'
let apiUrl = 'http://192.168.1.10/honeybee/HoneyApi/';
#Injectable()
export class RestapiProvider {
token:any;
constructor(public http: HttpClient) {
console.log('Hello RestapiProvider Provider');
}
getUsers(credentials, type) {
return new Promise((resolve, reject) => {
var headers = new HttpHeaders();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept','application/json');
headers.append('Content-Type','application/json');
this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
.subscribe((res: Response) => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
}
I have included the FormsModule in app.module.ts. Any help is much appreciated.
Since you are using HttpClient, you dont have to generally use result.json();
this.responseData = result;
Also you do not have to use Promise, change the service code as follows,
getUsers(credentials, type) {
var headers = new HttpHeaders();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept','application/json');
headers.append('Content-Type','application/json');
return this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers});
}
and in your component,
this.restProvider.getUsers(this.userData,'user_Login').subscribe((data) => {
console.log(data);
});

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

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

Not able to display data from post in ionic

I'm trying to get data that I get from a post call and display in my html page in ionic.
My Ts code is
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '#angular/common/http';
#IonicPage()
#Component({
selector: 'page-fashion',
templateUrl: 'fashion.html',
})
export class FashionPage {
users: any;
body: Object = {
"id": 1014,
"filter": null,
"lat": 13.05831,
"lng": 80.21195,
"mapRadius": 5,
"pageSize": 50,
"pageStart": 1,
"priceRangeFrom": 0,
"priceRangeTo": 100000
};
constructor(public navCtrl: NavController, public navParams: NavParams, public httpClient: HttpClient) {
this.users = this.httpClient.post('myapi',this.body);
this.users.subscribe(data => {
this.users = data;
console.log('my data: ', data);
console.log("the users data ------------>",this.users);
})
}
}
And my html page is
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Fashion</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list inset>
<ion-item *ngFor="let user of (users | async) ">
<h2>{{user.Name}}</h2>
<p>Price : {{user.Price}}</p>
</ion-item>
</ion-list>
</ion-content>
The error is InvalidPipeArgument: '[object Object]
but i am also getting the data before the error message comes, so when i click on close on the above image i am getting my data, but i need to get it as soon as get into the page
EDIT1: I am Getting the data only when i switch to a different tab and come back to this
EDIT2: Guys a I forgot to mention what my api returns, It gives me [34]
i.e.
[{
....
},
..
].
There is an error in your aync pipe declaration it should be like below . Also you are using the same users property to create the Observable and store the data. Create a new property to store the data.
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Fashion</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list inset>
<ion-item *ngFor="let user of userData | async ">
<h2>{{user.Name}}</h2>
<p>Price : {{user.Price}}</p>
</ion-item>
</ion-list>
</ion-content>
edit : create a new property like userData:any[] = [] in your component as use it like below -
export class FashionPage {
users: any;
userData:any[] = []
body: Object = {
"id": 1014,
"filter": null,
"lat": 13.05831,
"lng": 80.21195,
"mapRadius": 5,
"pageSize": 50,
"pageStart": 1,
"priceRangeFrom": 0,
"priceRangeTo": 100000
};
constructor(public navCtrl: NavController, public navParams: NavParams, public httpClient: HttpClient) {
this.users = this.httpClient.post('myapi',this.body);
this.users.subscribe(data => {
this.userData = data;
console.log('my data: ', data);
console.log("the users data ------------>",this.userData);
})
}
}
Initialize users: any; as users = []; since async requires an
observable or an array
Also change the variable name of subscription,
this.users = this.httpClient.post('myapi',this.body);
to,
this.userResult = this.httpClient.post('myapi',this.body);
change html to <ion-item *ngFor="let user of users | async ">
HTML:
<ion-item *ngFor="let user of users | async ">
<h2>{{user.Name}}</h2>
<p>Price : {{user.Price}}</p>
</ion-item>
So TS:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '#angular/common/http';
#IonicPage()
#Component({
selector: 'page-fashion',
templateUrl: 'fashion.html',
})
export class FashionPage {
users: any;
....
constructor(public navCtrl: NavController, public navParams: NavParams, public httpClient: HttpClient) {
this.userResult = this.httpClient.post('myapi',this.body);
this.userResult.subscribe(data => {
this.users = data;
console.log('my data: ', data);
console.log("the users data ------------>",this.users);
})
}
}
The api returns me [34], i.e. array of 34 objects in it.
I needed a separate variable to store the data and to call the api.
So the code that works to get me the data is
HTML code
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Fashion</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list inset>
<ion-item *ngFor="let user of userData">
<h2>{{user.Name}}</h2>
<p>Price : {{user.Price}}</p>
</ion-item>
</ion-list>
</ion-content>
TS code
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '#angular/common/http';
#IonicPage()
#Component({
selector: 'page-fashion',
templateUrl: 'fashion.html',
})
export class FashionPage {
users: any;
userData = [];
body: Object = {
"id": 1014,
"filter": null,
"lat": 13.05831,
"lng": 80.21195,
"mapRadius": 5,
"pageSize": 50,
"pageStart": 1,
"priceRangeFrom": 0,
"priceRangeTo": 100000
};
constructor(public navCtrl: NavController, public navParams: NavParams, public httpClient: HttpClient) {
this.users = this.httpClient.post('myapi',this.body);
this.users.subscribe(data => {
this.userData = data;
console.log('my data: ', data);
console.log("the users data ------------>",this.userData);
})
}
}
You guys are always wonderful,this community has never failed me once...Thanks a million to all for your valuable time to get me the answer!!!!!!!!

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

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>