android http request doesn't work on android device or android emulator - ionic-framework

so i just created this ionic app, and I put a http request method on it for test, the problem is win I build the app for android the http method doesn't work.
But it works fine win a build it for iOS,
This is my ionic info:
ionic (Ionic CLI) : 4.6.0 (/Users/us/node_modules/ionic)
Ionic Framework : ionic-angular 3.9.5
#ionic/app-scripts : 3.2.2
Cordova:
cordova (Cordova CLI) : 9.0.0 (cordova-lib#9.0.1)
Cordova Platforms : android 8.0.0, ios 5.0.1
Cordova Plugins : cordova-plugin-ionic 5.3.1, cordova-plugin-
ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 4.1.1, (and 6
other plugins)
System:
ios-sim : 8.0.1
NodeJS : v10.15.1 (/usr/local/bin/node)
npm : 6.9.0
OS : macOS High Sierra
Xcode : Xcode 10.1 Build version 10B61
my page.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Http } from '#angular/http';
import "rxjs/add/operator/map"
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
list_car:any;
constructor(public navCtrl: NavController, public http: Http) {
//check if the omra section exist or not
this.http.get("http://android.page.com/2omra_details.php")
.map(res
=> res.json().omra)
.subscribe(data => {
this.list_car = data;
console.log(this.list_car);
})
}
}
Any suggestions to what I may be doing wrong?

Your endpoint not working
Try with sample data API example
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/retry';
#Injectable()
export class ApiService {
url: string = 'https://api.chucknorris.io/jokes/random';
url2: string = 'https://api.spacexdata.com/v2/launches/latest';
constructor(private http: HttpClient) {}
getData(): Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.url).retry(3);
}
getOtherData(): Observable<any> {
return this.http.get<any>(this.url2).retry(3);
}
}
export interface ApiResponse {
icon_url: string;
id: string;
url: string;
value: string;

Related

Property 'dismiss' does not exist on type 'ModalController'

I'm following this doc about Modal in Ionic Angular (https://ionicframework.com/docs/api/modal).
I've found this problem and cannot figure out the way to solve.
I'm currently using this version: #ionic/app-scripts : 3.2.4
import { IonicPage, NavController, NavParams, ModalController } from 'ionic-angular';
dismiss() {
this.modalController.dismiss({
'dismissed': true
});
}
Error:
Property 'dismiss' does not exist on type 'ModalController'.ts(2339)
Try changing your import to this:
import { ModalController } from '#ionic/angular';

I'm having the following error with my ionic application when working with the BarcodeScanner

I am developing an application to read codes that I am using the BarcodeScanner but when I execute the application on my device I get the following error
**
**Error running it on my iphone 6 using ionic DevApp Error Runtime Error Object(_WEBPACK_IMPORTED_MODULE_1_ionic_native_core_["cordova"])is not a function. (In 'Object(_WEBPACK_IMPORTED_MODULE_1_ionic_native_core_["cordova"])(this, "scan", {"callbackOrder":"reverse"}, arguments)', 'Object(_WEBPACK_IMPORTED_MODULE_1_ionic_native_core_["cordova"])'is an instance of Object)
Error that is displayed when executing it in ionic serve, ERROR TypeError: Object(...) is not a function at BarcodeScanner.scan (index.js:31) at MenuPage.webpackJsonp.101.MenuPage.scanQR (menu.ts:53) at Object.eval [as handleEvent] (MenuPage.html:17) at handleEvent (core.js:13589) at callWithDebugContext (core.js:15098) at Object.debugHandleEvent [as handleEvent] (core.js:14685) at dispatchEvent (core.js:10004) at core.js:10629 at HTMLButtonElement. (platform-browser.js:2628) at t.invokeTask (polyfills.js:3) **
at the beginning I had the error that my app-module.ts did not
recognize me the BarcodeScanner because when calling it in providers
me, TS2322: Type 'BarcodeScannerOriginal' is not assignable to type
'Provider'. Type 'BarcodeScannerOriginal' is not assignable to type
'FactoryProvider'. Property 'provide' is missing in type
'BarcodeScannerOriginal'
**
Menu.html
<ion-header class="toolbar">
<ion-navbar>
<ion-title>Scan</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding class="Scan">
<div class="row">
<div class="col">
<h2>Scan your QR Code Here</h2>
</div>
<div class="col">
<h3>{{eventTitle}}</h3>
</div>
</div>
<button ion-button block color="secondary" class="Scan-button" (click)="scanQR()" [disabled]="loading">{{buttonText}}</button>
</ion-content>
Menu.ts
import { Component } from '#angular/core';
import {Platform} from "ionic-angular";
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { ToastController } from 'ionic-angular';
import { BarcodeScanner, BarcodeScannerOptions } from '#ionic-native/barcode-scanner/ngx';
/**
* Generated class for the MenuPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-menu',
templateUrl: 'menu.html',
})
export class MenuPage {
public scannedText: string;
public buttonText: string;
public loading: boolean;
private eventId: number;
public eventTitle: string;
num: string;
// #ts-ignore
constructor(private _nav: NavController,
private _navParams: NavParams,
private _barcodeScanner: BarcodeScanner) {
}
ionViewDidLoad() {
this.eventId = this._navParams.get('eventId');
this.eventTitle = this._navParams.get('eventTitle');
this.buttonText = "Scan";
this.loading = false;
}
public scanQR() {
this.buttonText = "Loading..";
this.loading = true;
this._barcodeScanner.scan().then((barcodeData) => {
if (barcodeData.cancelled) {
console.log("User cancelled the action!");
this.buttonText = "Scan";
this.loading = false;
return false;
}
console.log("Scanned successfully!");
console.log(barcodeData);
this.goToResult(barcodeData);
}, (err) => {
console.log(err);
});
}
private goToResult(barcodeData) {
this._nav.push(ScanResultPage, {
scannedText: barcodeData.text
});
}
}
app-module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import {MenuPage} from "../pages/menu/menu";
import { BarcodeScanner } from '#ionic-native/barcode-scanner/ngx';
import { HttpClientModule } from '#angular/common/http';
import { FormsModule } from '#angular/forms';
import {HttpModule} from "#angular/http";
// #ts-ignore
#NgModule({
declarations: [
MyApp,
HomePage,
MenuPage
],
imports: [
BrowserModule, HttpClientModule,
IonicModule.forRoot(MyApp),
HttpModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
MenuPage
],
providers: [
StatusBar,
SplashScreen,
BarcodeScanner,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
enter image description here
My guess is you are on Ionic 3 but you are using the native plugin version supported for Ionic 4.
Solution
Uninstall both cordova and ionic native plugin
$ionic cordova plugin remove phonegap-plugin-barcodescanner
$npm uninstall #ionic-native/barcode-scanner
Install version 4.
$ ionic cordova plugin add phonegap-plugin-barcodescanner
$ npm install --save #ionic-native/barcode-scanner#4
And don't append ngx at the end of the import.
import { BarcodeScanner } from '#ionic-native/barcode-scanner';
Note
If you are using Ionic 3, try following the Ionic v3 guide instead of the latest guide
Ionic v3 guide:https://ionicframework.com/docs/v3/native/barcode-scanner/
For complete explanation you can find my other answer here: https://stackoverflow.com/a/54474247/6617276

Network service not working in browser

I've written a provider to help track network connectivity using the Native Network plugin:
import { Injectable } from '#angular/core';
import { Network } from '#ionic-native/network';
import { Platform } from 'ionic-angular';
#Injectable()
export class Connectivity {
public online: boolean = false;
constructor(private network: Network) {
this.network.onDisconnect().subscribe(() => {
console.log('Network offline');
this.online = false;
});
this.network.onConnect().subscribe(() => {
this.online = true;
console.log('Network online');
});
});
}
}
I've installed the relevent plugins (package.json):
"cordova-plugin-network-information": "^2.0.1",
...
"#ionic-native/network": "^4.7.0",
And I've included my provider in my app.module.ts:
providers: [
Network,
StatusBar,
SplashScreen,
Connectivity,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
Yet, when I run the app in the browser, neither of the observables fire. If I try print: console.log(this.network.type) in the provider constructor, it just prints null.
The answer here is that the native network plugin doesn't work in the browser. Even though it has "browser" listed as a supported platform:
It is referring to the Cordova Browser which is different to a web browser. I found this out after discussion on the Ionic Slack channel.
You need to instead write a Provider that:
Detects platform
If on a native device, use the native network plugin
If in a browser, use the browser API
For others with the same problem:
Here is some clarification on why you have two different APIs available
Here is an example of a provider that uses a variety of approaches for finding location (this isn't the same as my question, but is similar in the solution as it uses a browser API as well as the Ionic Native API)
In my application I use "cordova-plugin-network-information": "^ 2.0.1"
and "#ionic-native / network": "^ 4.6.0"
I can share the same service I use. this is currently working
'# angel / core' import {Injectable};
From the '# Ionic-native / network' resource {Network};
import { Injectable } from '#angular/core';
import { Network } from '#ionic-native/network';
#Injectable()
export class NetworkProvider {
constructor(private _network: Network) { }
isConnectInternet() {
return this._network.onConnect();
}
isDisconnect() {
return this._network.onDisconnect();
}
enter code here
connectionType() {
if (this._network.type == 'none' ) {
return false;
} else {
return true;
}
}
}
I am using this service into my project which is on following environment
cli packages:
#ionic/cli-utils : 1.19.2
ionic (Ionic CLI) : 3.20.0
global packages:
cordova (Cordova CLI) : 8.0.0
this is my provider file, network.ts.
import { Functions } from './../functions';
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Network } from '#ionic-native/network';
import { Events } from 'ionic-angular';
/*
Generated class for the NetworkProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
export enum ConnectionStatusEnum {
Online,
Offline
}
#Injectable()
export class NetworkProvider {
previousStatus;
constructor(public functions:Functions,
public network: Network,
public eventCtrl: Events) {
this.previousStatus = ConnectionStatusEnum.Online;
}
public initializeNetworkEvents(): void {
this.network.onDisconnect().subscribe(() => {
if (this.previousStatus === ConnectionStatusEnum.Online) {
this.eventCtrl.publish('network:offline');
}
this.previousStatus = ConnectionStatusEnum.Offline;
});
this.network.onConnect().subscribe(() => {
if (this.previousStatus === ConnectionStatusEnum.Offline) {
this.eventCtrl.publish('network:online');
}
this.previousStatus = ConnectionStatusEnum.Online;
});
}
make sure that you are running
ionic cordova run browser
not
ionic serve

Ionic 3 - Yelp API

I created a brand new Ionic project to run this code. It worked fine in Postman but when I run ionic serve I get an error.
home.ts :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Http, Headers, RequestOptions, HttpModule } from '#angular/http';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
restaurants: any;
constructor(public navCtrl: NavController, public http: Http) {
var headers = new Headers();
headers.append('Authorization', 'Bearer XX');
var options = new RequestOptions({headers: headers});
this.http.get('https://api.yelp.com/v3/businesses/search?latitude=XX&longitude=XX&radius=10000&categories=food&locale=en_NZ', options).map(res => res.json()).subscribe(data => {
this.restaurants = data.data.children;
console.log(this.restaurants);
});
}
}
When I run ionic serve, I see the following error in the console:
For ionic serve you may use Chrome plugin: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en or any other.
In any case you will need also to add Yelp API address to your index.html to deal with CSP.
See information about CSP here: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/

Ionic ENOENT: no such file or director

I am using Ionic.
Cordova CLI: 6.4.0
Ionic Framework Version: 3.1.1
Ionic CLI Version: 2.1.18
Ionic App Lib Version: 2.1.9
Ionic App Scripts Version: 1.3.0
ios-deploy version: Not installed
ios-sim version: Not installed
OS: macOS Sierra
Node Version: v7.10.0
Xcode version: Xcode 8.3.2 Build version 8E2002
I get the following error:
core.es5.js:1084 ERROR Error: Uncaught (in promise): Error: Module build failed: Error: ENOENT: no such file or directory, open
'/Users/richardmarais/Development/ionic/theWhoZoo/src/pages/model/ratingModel.js'
Error: Module build failed: Error: ENOENT: no such file or directory, open
'/Users/richardmarais/Development/ionic/theWhoZoo/src/pages/model/ratingModel.js'
When I try access the following page:
review/review.ts
...
import { RatingModel } from '../model/ratingModel';
#IonicPage()
#Component({
templateUrl: 'review.html'
})
export class ReviewPage {
...
model/ratingModel.ts
import { Injectable } from "#angular/core";
import { PersonModel } from './personModel';
import { JobModel } from './jobModel';
#Injectable()
export class RatingModel {
public id: number = null;
public job: JobModel = null;
public review: string = null;
public rating: number = null;
public reviewDate: number = null;
public time: string = null;
public person: PersonModel = null;
public anonymous: number = null;
}
This was working until I changed my pages to use lazy loading.
review/review.module.ts
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { ReviewPage } from './review';
import { ControlMessagesModule } from '../validation/controlMessages.module';
import { RatingComponentUpdateableModule } from '../utils/rating/ratingComponentUpdateable.module';
#NgModule({
declarations: [ReviewPage],
imports: [IonicPageModule.forChild(ReviewPage), ControlMessagesModule, RatingComponentUpdateableModule],
exports: [ReviewPage]
})
export class ReviewPageModule { }
UPDATE
I find the error occurs because of the following:
this.ratingModel = navParams.get('ratingModel');
if (!this.ratingModel) {
this.ratingModel = new RatingModel();
when I remove the new RatingModel() line, I don't get any errors.
How are you supposed to create a new RatingModel?
The problem here is you are making the model class an injectable.
#Injectable()
export class RatingModel {
You dont have to make a model class as injectable.
If you do need to do so, you will have to set it as a provider.
Or try to get an object from the explicit injector.
constructor(private injector: Injector) { }
//..
this.ratingModel = this.injector.get(RatingModel)