Rest web service returns null value on mobile device but works on PC in Ionic App - rest

i am consuming Rest JSONP Web Service in an ionic App which works fine on PC but returns null value on mobile devices
My page.ts file
import {
Component,
OnInit
} from '#angular/core';
import {
AlertController,
LoadingController
} from '#ionic/angular';
import {
ActionSheetController
} from '#ionic/angular';
import {
Router
} from '#angular/router'
import {
ProApiService
} from './../../../../services/pro-api.service';
#Component({
selector: 'app-ranked-diagnosis',
templateUrl: './ranked-diagnosis.page.html',
styleUrls: ['./ranked-diagnosis.page.scss'],
})
export class RankedDiagnosisPage implements OnInit {
tabSelect: string = 'show10';
show10Data: Array < any >= [];
showAllData: Array < any >= [];
redFlagsData: Array < any >= [];
loading: any;
constructor(
private api: ProApiService,
public alertController: AlertController,
public loadingController: LoadingController,
public actionSheetController: ActionSheetController,
private router: Router
) {}
segmentChanged(event: any) {
this.tabSelect = event.detail.value;
}
async presentActionSheet(buttons) {
const actionSheet = await this.actionSheetController.create({
header: 'Sub Diagnosis',
buttons: buttons
});
await actionSheet.present();
}
async presentAlert(msg: string, header: string) {
const alert = await this.alertController.create({
header: '',
subHeader: header,
message: msg,
buttons: ['OK']
});
await alert.present();
}
async presentLoading() {
this.loading = await this.loadingController.create({
message: 'loading...',
});
return await this.loading.present();
}
ngOnInit() {
}
ionViewWillEnter() {
if (this.api.ProApiData.diagnoses_checklist.diagnoses) {
this.showAllData =
this.api.ProApiData.diagnoses_checklist.diagnoses;
for (let i = 0; i < 10; i++) {
this.show10Data.push(this.showAllData[i]);
}
this.showAllData.forEach(item => {
if (item.red_flag == 'true') {
this.redFlagsData.push(item);
}
});
console.log(this.showAllData);
} else {
console.log('error');
this.router.navigateByUrl('isabel-pro');
}
}
why_diagnosis(url: any, weightage: any) {
this.presentLoading();
this.api.why_diagnosisApi(url).subscribe(res => {
let matched_terms = res._body.why_diagnosis.matched_terms;
console.log(matched_terms);
let alertMsg = `We matched the terms: ${matched_terms}<br><hr>Degree of match between query entered and database: ${weightage}`;
this.presentAlert(alertMsg, 'Why did this diagnosis come up ?');
this.loadingController.dismiss();
}, err => {
this.loadingController.dismiss();
console.log('error');
});
}
}
in the above code i am calling why_diagnosis function which calls the function from a service file.
My service.ts file
import {
Injectable
} from '#angular/core';
import {
HttpClient,
HttpHeaders
} from '#angular/common/http';
import {
Jsonp
} from '#angular/http';
import {
Observable
} from 'rxjs';
import {
map
} from 'rxjs/operators';
import {
ConstantsService
} from './../../../services/constants.service';
#Injectable({
providedIn: 'root'
})
export class ProApiService {
apiRoot = this.root.APIroot;
diagnosisPROData: any;
drugData: any;
ProApiData: any;
drugApiData: any;
constructor(
private jsonp: Jsonp,
private http: HttpClient,
private root: ConstantsService) {}
why_diagnosisApi(url: any): Observable < any > {
let whyUrl = `${this.apiRoot}Mob_isabelPRO.php?
why_url=${url}&callback=JSONP_CALLBACK`;
return this.jsonp.request(whyUrl, 'callback')
.pipe(
map(
res => {
let why_diagnosis = res;
return why_diagnosis;
}
)
);
}
}
above code is from my service file.
this is the value i am getting in PC
this is the return on mobile
i dont know whats wrong with it. please suggest me the solution
Thanks

Related

How to creat a dynamic text

I have a list of titles, and I would like these texts to alternate as I switch to ion-select. How do I do this?
I have no idea how to do this, not even what part of the code to show. I made an attempt here but whenever I use the console the value returned is undefined.
My typescrit code:
import { Titulo } from './../Services/services.service';
import { DataService } from './data.service';
import { Component, OnInit, ViewChild} from '#angular/core';
import {IonSlides} from '#ionic/angular';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-libertacao',
templateUrl: './libertacao.page.html',
styleUrls: ['./libertacao.page.scss'],
})
export class LibertacaoPage implements OnInit {
#ViewChild(IonSlides) slides: IonSlides;
PAGINA_SELECIONADA: number;
// tslint:disable-next-line: variable-name
index_atual: number;
titulo: Titulo;
constructor(private dataservice: DataService, private activatedRoute: ActivatedRoute ){
}
ngOnInit() {
const id = this.activatedRoute.snapshot.paramMap.get('id');
this.titulo = this.dataservice.getTituloById(parseInt(id, 10));
}
OnChange(event: any)
{
if (event.detail.value === this.PAGINA_SELECIONADA) {
this.slides.slideTo(this.PAGINA_SELECIONADA);
}
else {}
console.log(this.titulo);
}
slideChanged() {
this.slides.getActiveIndex().then((index) => {
this.index_atual = index;
});
}
}

Error cannot find module cryptojs in waves-crypto npm module

I am trying to use #waves/waves-crypto I have import * as wavesCrypto from '#waves/waves-crypto' in my .ts file but I am still getting error within the npm module itself. I am trying to create a waves wallet using nativescript and right now I am trying to create the address and seed and public and private key for the user. this is login.ts where im calling the #waves/waves-crypto
import { Component, ElementRef, ViewChild } from "#angular/core";
import { Router } from "#angular/router";
import { alert, prompt } from "tns-core-modules/ui/dialogs";
import { Page } from "tns-core-modules/ui/page";
import { Routes } from "#angular/router";
//import { publicKey, verifySignature, signBytes, address, keyPair, privateKey } from "../#waves/waves-crypto";
import * as wavesCrypto from '../#waves/waves-crypto';
import { User } from "../shared/user.model";
import { UserService } from "../shared/user.service";
#Component({
selector: "app-login",
moduleId: module.id,
templateUrl: "./login.component.html",
styleUrls: ['./login.component.css']
})
export class LoginComponent {
isLoggingIn = true;
user: User;
#ViewChild("password") password: ElementRef;
#ViewChild("confirmPassword") confirmPassword: ElementRef;
#ViewChild("waves") waves: ElementRef;
constructor(private page: Page, private userService: UserService, private router: Router) {
this.page.actionBarHidden = true;
this.user = new User();
// this.user.email = "foo2#foo.com";
// this.user.password = "foo";
const seed = 'magicseed';
const pubKey = wavesCrypto.publicKey(seed);
const bytes = Uint8Array.from([1, 2, 3, 4]);
const sig = wavesCrypto.signBytes(bytes, seed);
const isValid = wavesCrypto.verifySignature(pubKey, bytes, sig)
}
wallet() {
let walletAddress = wavesCrypto.address('seed', 'T');
let keyPair = wavesCrypto.keyPair('seed');
//publicKey('seed');
//privateKey('seed');
wavesCrypto.privateKey('seed');
alert(walletAddress);
console.log(walletAddress);
console.log(keyPair);
}
toggleForm() {
this.isLoggingIn = !this.isLoggingIn;
}
submit() {
if (!this.user.email || !this.user.password) {
this.alert("Please provide both an email address and password.");
return;
}
if (this.isLoggingIn) {
this.login();
} else {
this.register();
}
}
login() {
this.userService.login(this.user)
.then(() => {
this.router.navigate(["/home"]);
})
.catch(() => {
this.alert("Unfortunately we could not find your account.");
});
}
register() {
if (this.user.password != this.user.confirmPassword) {
this.alert("Your passwords do not match.");
return;
}
this.userService.register(this.user)
.then(() => {
this.alert("Your account was successfully created.");
this.isLoggingIn = true;
})
.catch(() => {
this.alert("Unfortunately we were unable to create your account.");
});
}
forgotPassword() {
prompt({
title: "Forgot Password",
message: "Enter the email address you used to register for APP NAME to reset your password.",
inputType: "email",
defaultText: "",
okButtonText: "Ok",
cancelButtonText: "Cancel"
}).then((data) => {
if (data.result) {
this.userService.resetPassword(data.text.trim())
.then(() => {
this.alert("Your password was successfully reset. Please check your email for instructions on choosing a new password.");
}).catch(() => {
this.alert("Unfortunately, an error occurred resetting your password.");
});
}
});
}
focusPassword() {
this.password.nativeElement.focus();
}
focusConfirmPassword() {
if (!this.isLoggingIn) {
this.confirmPassword.nativeElement.focus();
}
}
alert(message: string) {
return alert({
title: "APP NAME",
okButtonText: "OK",
message: message
});
}
}
I have the same problem and I opened the next issue on the Github repo (you can go and click like or comment), link here
In the issue I explain a workaround that is working for me to validate a signature, you can use the same snippet.
First import manually the submodules needed:
import { default as axlsign } from '#waves/signature-generator/libs/axlsign';
import { default as convert } from '#waves/signature-generator/dist/utils/convert';
import { concatUint8Arrays } from '#waves/signature-generator/dist/utils/concat';
import { default as base58 } from '#waves/signature-generator/dist/libs/base58';
Then you can use the next code to validate the signature and publickey:
let prefix = "WavesWalletAuthentication";
let host = new URL(yourServerUrl).hostname;
let user = wavesAddressString;
let payload = theStringThatWasSigned;
let data = [prefix, host, payload]
.map(d => convert.stringToByteArrayWithSize(d))
.map(stringWithSize => Uint8Array.from(stringWithSize));
let dataBytes = concatUint8Arrays(...data);
let publicKeyBytes = base58.decode(publicKeyOnBase58Format);
let signatureBytes = base58.decode(signatureOnBase58Format);
let validSignature = axlsign.verify(publicKeyBytes, dataBytes, signatureBytes);
console.log("(login) validSignature?", validSignature);

IONIC-3 NavController throwing can't resolve all parameters error

I have an interesting problem with IONIC-3 that I've not been able to solve. I am attempting to implement an auth routing which is triggered by ionViewCanEnter. However, while I can pass one nav setter, it will not allow multiple. Here is the code:
AuthService Function:
isAuthenticated(nav: NavController): boolean | Promise<any> {
const userAuth = this.uData.getAuthenticated;
const userProfile = this.uData.getUserProfile;
if (userAuth ) {
//User is logged in, so let's check a few things.
if (!userProfile.sign_up_complete) {
//User has not completed sign up
setTimeout(() => { nav.setRoot(CreateAccountPage) }, 0);
}
return true
} else {
//User is not authenticated, return to walkthrough
setTimeout(() => { nav.setRoot(WalkthroughPage) }, 0);
return false
}}
Example calling:
ionViewCanEnter(): boolean | Promise<any> {
return this.auth.isAuthenticated(this.nav);
}
If I have only CreateAccountPage, the script runs fine. However, when I add WalkthroughPage, it throws the following error:
Error: Can't resolve all parameters for ListingPage: (?, [object Object], [object Object], [object Object]).
Which is an error related to the AuthService. For clarity the WalkthroughPage code is as follows:
import { Component, ViewChild } from '#angular/core';
import { IonicPage, NavController, Slides } from 'ionic-angular';
import { RemoteConfigProvider } from '../../providers/remote-config/remote-config';
import { LoginPage } from '../login/login';
import { SignupPage } from '../signup/signup';
#IonicPage()
#Component({
selector: 'walkthrough-page',
templateUrl: 'walkthrough.html'
})
export class WalkthroughPage {
lastSlide = false;
sign_up_enabled: null;
sign_in_enabled: null;
#ViewChild('slider') slider: Slides;
constructor(public nav: NavController,
public remoteConfig: RemoteConfigProvider) {
}
ionViewDidLoad() {
this.remoteConfig.getValue('sign_up_enabled').then(t => {
this.sign_up_enabled = t;
})
this.remoteConfig.getValue('sign_in_enabled').then(t => {
this.sign_in_enabled = t;
})
}
skipIntro() {
this.lastSlide = true;
this.slider.slideTo(this.slider.length());
}
onSlideChanged() {
this.lastSlide = this.slider.isEnd();
}
goToLogin() {
this.nav.push(LoginPage);
}
goToSignup() {
this.nav.push(SignupPage);
}
}
I have attempted to compare both pages, but not identified the exact cause. I welcome any thoughts.
For those who encounter a similar issue, the fix was straight forward. I simply used deep-linking reference which resolved all issues. Example below.
isAuthenticated(nav: NavController): boolean | Promise<any> {
const userAuth = this.userStore.getAuthenticated;
const userProfile = this.userStore.getUserProfile;
if (userAuth) {
return true
} else {
console.log('Auth guard: Not authenticated');
setTimeout(() => { nav.setRoot('no-access') }, 0);
return false
}
}

IONIC 2 - Cannot retrieve array inside ionViewDidLoad()

I want to retrieve places coordinates from restApi and display them on the map.
I got error : Cannot read property 'length' of undefined
Please help me !
I want you to tell me how i can get my data in order to add multiple markers.
This is my portion of code
import { Component, ViewChild, ElementRef } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '#ionic-native/geolocation';
import { RestProvider } from '../../providers/rest/rest';
declare var google;
#Component({
selector: 'page-localisation',
templateUrl: 'localisation.html',
})
export class LocalisationPage {
#ViewChild('map') mapElement: ElementRef;
map: any;
places: Array<any>;
errorMessage : string;
constructor(public navCtrl: NavController, public navParams: NavParams, public geolocation: Geolocation, public rest: RestProvider) {
}
ionViewDidLoad(){
this.loadMap();
this.getPlaces();
this.addPlacesToMap()
console.log("Length : " + this.places.length) ; //Error Cannot read property 'length' of undefined
}
getPlaces() {
this.rest.getPlaces().subscribe(
places => this.places = places,
error => this.errorMessage = <any>error
);
}
loadMap(){
let latLng = new google.maps.LatLng(-4.066548, 5.356315);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}
addPlacesToMap(){
//...
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
});
content: content
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
}
ionViewDidLoad is launched before "this.rest.getPlaces().subscribe" is finished... So your variable "places" is NULL
Change getPlaces to a Promise
async getPlaces() {
places = await this.rest.getPlaces() ;
return places
}
Then in ionViewDidLoad
ionViewDidLoad(){
var that = this ;
this.loadMap();
this.getPlaces().then((places)=>{
that.places = places;
console.log("Length : " + that.places.length) ;
});
this.addPlacesToMap()
}

Angular2 REST API

I learn Angular2 and now i try to get my data from a rest service. My rest service works and i can get data from there.
But angular always give my this error message: JSON.parse: unexpected character at line 1 column 1 of the JSON data
This is my Service:
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { Person } from '../_models/person';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class PersonService {
private headers: Headers;
constructor(private http: Http)
{
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
}
getPersons(): Observable<Person[]> {
return this.http.get('http://localhost:54612/api/Person')
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
private handleError(error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
This is the component for the view:
import { Component, OnInit } from '#angular/core';
import { Person } from '../_models/person';
import { PersonService } from '../_services/person.service';
#Component({
moduleId: module.id,
templateUrl: 'login.component.html',
providers: [ PersonService ]
})
export class LoginComponent implements OnInit {
errorMessage: string;
personen: Person[] = [];
constructor(private personService: PersonService) { }
ngOnInit() { this.getPersons(); }
getPersons() {
this.personService.getPersons()
.subscribe(
personen => this.personen = personen,
error => this.errorMessage = <any>error);
}
}
And this is my view:
<h1>Tour of Heroes</h1>
<h3>Heroes:</h3>
<ul>
<li *ngFor="let person of personen">{{person.IDPerson}}</li>
</ul>
<p class="error" *ngIf="errorMessage">{{errorMessage}}</p>
Your server is return XML. The reason is probably because it's the default when you don't explicitly set the Accept to something else. You have set it in the Headers to JSON, but you never add the headers to the request. You need to do
this.http.get('http://localhost:54612/api/Person', { headers: this.headers });
Try this snippet, in your getPersons()
return this.http.get('http://localhost:54612/api/Person',{headers: this.headers })
.map((response:Response) => response.json())