No requests during tns debug - android

this is my first app in nativescript and in mobile development environment in general. And I am having some difficulties. What I am trying is to make some dummy http requests with angular http module but for some reason when I debug the app inside chrome no requests seem to be made.
Here is my code:
template:
<Page>
<StackLayout>
<Button text="GET" (tap)="get()"></Button>
<Button text="POST" (tap)="post()"></Button>
</StackLayout>
</Page>
component:
import { Component } from "#angular/core";
import { AuthService } from "../../shared/auth.service";
import { HttpClient } from "#angular/common/http";
#Component({
selector: "register",
moduleId: module.id,
templateUrl: "./register.component.html"
})
export class RegisterComponent {
constructor(private auth: AuthService, private http: HttpClient) {}
get()
{
console.log('GET');
this.http.get('https://httpbin.org/get');
}
post()
{
console.log('POST');
this.http.post('https://httpbin.org/post', null);
}
}
Now when those functions execute there are no logged requests.
I am running inside an emulator and I can browse from it just fine so if someone has some ideas on what could be wrong...

You have to subscribe to the http requests else they are only defined and not called, try adding the following after this.http.get('https://httpbin.org/get') and this.http.post('https://httpbin.org/post', null):
.subscribe(
res => console.log(res),
err => console.log(err),
() => console.log("Done"),
);
Edit
I didn't mention originally, it's actually best to subscribe to the function that returns the http method, instead of subscribing to the call itself. From experience, I have found some unusual behaviour can occur

Related

how to debug network responce in react native

i am trying to debug my code in react native here i have a axios post request the only responce is i get when there is a error is axios error
rather than that i am looking to debug my code just like in react js by inspect element and network tab
currently i open my app using npx react-native run-andoid this opens the app in a emulator and is really diffcult to debug my code can anyone suggest a better method for debugiing
var Data56 = {
name: name,
email: email,
babyname: babyname,
phone: nuber,
baby_date: date,
};
}
axios
.post('http://10.0.2.2:8000/api/register', Data56, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then(res => {
props.navigation.navigate('Home_scrren', {data: Data56});
})
.catch(error => {
alert(error);
});
}
Follow this Step:-
(1) First you need to shake the device and open the debug option, it will redirect you to chrome.
(2) You need to inspect that and open the console tab.
(3) You need to add breakpoints in VSCode or add breakpoints using chrome.
(4) then simply Reload the application, using that you can do step-by-step debugging.
if (__DEV__) {
global.XMLHttpRequest = global.originalXMLHttpRequest
? global.originalXMLHttpRequest
: global.XMLHttpRequest;
global.FormData = global.originalFormData
? global.originalFormData
: global.FormData;
fetch; // Ensure to get the lazy property
if (window.__FETCH_SUPPORT__) {
// it's RNDebugger only to have
window.__FETCH_SUPPORT__.blob = false;
} else {
/*
* Set __FETCH_SUPPORT__ to false is just work for `fetch`.
* If you're using another way you can just use the native Blob and remove the `else` statement
*/
global.Blob = global.originalBlob ? global.originalBlob : global.Blob;
global.FileReader = global.originalFileReader
? global.originalFileReader
: global.FileReader;
}
}
add this code to root index.js
turn on debug
Check tab network like web,
we can see request and response,
one more option, you can add reactotron or flipper, this tool will log anything like network redux action..., without open debug mode
Hope this help you
1]firstly you can see this video
2]exapmle with axios
3] 2nd go to your console window and press D and see your emulator like this like this
if you press d in console window and see your output in your emulator
like this then then on the last option "Debug"
it will navigate to chrome screen here is screenshot
then write click on a screen and see option like inspect here is
screenshot
then then new screen will appear and go to consol tab there you can
see your data like this
I This this will help you
I'm using axios and fetch data and you can see in chrome i will get all data in debug mood also I'm my step which one I post here
import React, { useEffect, useState } from "react";
import { View, SafeAreaView, Text, StyleSheet, ScrollView, TouchableOpacity, FlatList } from "react-native";
import axios from "axios";
const App = () => {
const [list, setList] = useState([]);
useEffect(() => {
getList()
}, [])
const getList = () => {
axios({
url: "https://fakestoreapi.com/users?limit=5",
}).then((res) => {
var response = res.data;
console.log(response)
setList(response)
})
}
return (
<FlatList
data={list}
renderItem={({ item }) =>
<Text>{item}</Text>
}
/>
)
}
export default App;

Ionic get call not working in real android device (no error in console too)

I am on ionic 4. And I am using httpClient package to make the http calls. Nothing is happening when I hit the function. And I am not getting error in console too.
I know there are many answers for the same issue, but none of them worked for me.
I am importing as import { HttpClient, HttpHeaders } from '#angular/common/http';
My http service as below
this.http.get(fullurl)
.map(data => {
this.loading.dismiss();
console.log(data);
if(msg!="" && msg.length >= 0){
this.loading.dismiss();
}
The httpClient.get is an Observable. Which means you have to use like this:
import { HttpClient } from '#angular/common/http';
constructor(private http: HttpClient) { }
this.http.get(fullUrl)
.subscribe((data) => {
// Success handler
}, (error) => {
// Error handler
});

Ionic native Ibeacon ReferenceError: device is not defined

TLDR: Ibeacon module example does not work
I have a small app in Ionic 5 using capacitor.
I want to use the Ibeacon library, but I get the error :
Ressource for the library is scarse and I have only found people having issue when the delegate is undefined causing the LocatonManager error here.
I also tried to look what is causing the error, apparently the device mentioned is part of the device library. So I check if the Ibeacon library properly import the device one and it does in node_modules\cordova-plugin-ibeacon\plugin.xml, like so :
<!-- Version is set to anything because the only feature we use is the device.platform property which was available
since forever. The added benefit is that we don't force the consumers of this plugin to use a certain version of
the device plugin. -->
<dependency id="cordova-plugin-device" version="*" />
My class is pretty much the example given in the Ibeacon page:
import { Component, OnInit } from '#angular/core';
import { IBeacon } from '#ionic-native/ibeacon/ngx';
import { Platform } from '#ionic/angular';
#Component({
selector: 'app-beacon',
templateUrl: './beacon.page.html',
styleUrls: ['./beacon.page.scss'],
})
export class BeaconPage implements OnInit {
public beacons: any[] = [];
constructor(
private ibeacon: IBeacon,
private platform: Platform,
private _utils: UtilsService
) {}
ngOnInit() {
console.log('ngOnInit');
if (!this.platform.is('android')) {
console.log('Beacon related activity only available on Android');
return;
}
// create a new delegate and register it with the native layer
let delegate = this.ibeacon.Delegate();
console.log('delegate :', delegate);
// Subscribe to some of the delegate's event handlers
delegate.didRangeBeaconsInRegion().subscribe(
(data) => console.log('didRangeBeaconsInRegion: ', data),
(error) => console.error()
);
delegate.didStartMonitoringForRegion().subscribe(
(data) => console.log('didStartMonitoringForRegion: ', data),
(error) => console.error()
);
delegate.didEnterRegion().subscribe((data) => {
console.log('didEnterRegion: ', data);
});
let beaconRegion = this.ibeacon.BeaconRegion(
'deskBeacon',
'F7826DA6-ASDF-ASDF-8024-BC5B71E0893E'
);
this.ibeacon.startMonitoringForRegion(beaconRegion).then(
() => console.log('Native layer received the request to monitoring'),
(error) =>
console.error('Native layer failed to begin monitoring: ', error)
);
}
}
Also I imported the IBeacon module inside my module.ts like so :
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { IonicModule } from '#ionic/angular';
import { BeaconPageRoutingModule } from './beacon-routing.module';
import { BeaconPage } from './beacon.page';
import { IBeacon } from '#ionic-native/ibeacon/ngx';
#NgModule({
imports: [CommonModule, FormsModule, IonicModule, BeaconPageRoutingModule],
declarations: [BeaconPage],
providers: [IBeacon],
})
export class BeaconPageModule {}
Did I forget to do something ? Why is device undefined ? Should I also import the device library ?
I should mention I have the device library installed.
Inside the lib they use the device to check the plataform, that is the code:
BeaconRegion.isValidUuid = function (uuid) {
// https://github.com/petermetz/cordova-plugin-ibeacon/issues/328
// If we are on Android, then allow the UUID to be specified as a wild-card (omitted)
var isAndroid = device && device.platform === "Android";
if (uuid === BeaconRegion.WILDCARD_UUID && isAndroid) {
return true;
}
var uuidValidatorRegex = this.getUuidValidatorRegex();
return uuid.match(uuidValidatorRegex) != null;
};
You can check right here https://github.com/petermetz/cordova-plugin-ibeacon/blob/270ffbbc12159861a16e5e81481103c1e09139cb/www/model/BeaconRegion.js#L38
So, you have to install the following plugin-in https://ionicframework.com/docs/native/device
npm install cordova-plugin-device
npm install #ionic-native/device
ionic cap sync
Then the find this device reference and the problem will be solved.

Having trouble making an AJX call in Ionic 4

I am making an app that will fetch the MySQL data using AJAX request and will post some data in the Database. It's an issue that it is not making an AJAX call in my project
I am working on Ionic 4 and PHP-MySQL as Backend service
import { Component, OnInit } from '#angular/core';
import * as $ from 'jquery';
import { data } from 'jquery';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
public press() {
// tslint:disable-next-line:only-arrow-functions
$.ajax({
url: "demo_test.txt", // or any URL
success: function(result) {
$("#div1").html(result);
}});
}
}
I want to make an AJAX call from remote HTML, PHP or text file in my Ionic 4 App.
You should use httpclient from angular/http. that is very straight thing.
https://angular.io/guide/http
this.http.get(url).subscribe(data => {
console.log(data)
}, err => {
console.log(err)
}

IONIC 2 send message to multiple recipients

So developing this IONIC 2 app, I discoverd that sending SMS to multiple recipients isnt so trivial at it should be.
After a long research I've found this post where people trys to deal with multiple SMS. But even using their specs it doesnt work properly.
They say we can use an array of strings representing multiple phone numbers. So far so good, except it works only for the first number.
If someone has now details on this functionality I would love to hear about it.
Thanks
import { SMS } from '#ionic-native/sms';
constructor( private sms: SMS ){
this.sendSMS();
}
sendSMS() {
var MultiNumber = [ '1234567890' , '9876543210' ];
this.sms.send(MultiNumber, 'hello all this is testing message');
}
try this it is working for me, Hope it is working for you too.
So after ages of research over internet I got this litle jam called cordova-plugin-sms ( dont confuse it with cordova-sms-plugin ).
As it says in their documentation they have a function sendSMS which reeeally sends messages to multiple recipients.
So my solution for integrating it in IONIC 2 is as follows :
ionic cordova plugin add cordova-plugin-sms
and my Ionic 2 class is :
import { Component } from '#angular/core';
import { NavController, ToastController } from 'ionic-angular';
import { Http, Response } from "#angular/http";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
declare let window: any;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(private toastCtrl: ToastController, public navCtrl: NavController, public http: Http ) { }
ionViewDidLoad() {
this.startWhatchSMS();
}
// Android ONLY
startWhatchSMS() {
if (window.SMS) {
window.SMS.startWatch(() => {
//console.log("startWatch");
}, error => {
//console.log(error);
//console.log("error startWatch");
});
}
document.addEventListener('onSMSArrive', this.smsArived);
}
// Android ONLY
smsArived = (result: any) => {
//console.log(result);
let sms = result.data;
// put your code here...
}
sendTextMessage( ) {
window.SMS.sendSMS([ '1234567890' , '0987654321' ], 'Text message for multiple recipients',
(result) => {
console.log(result); // should be 'OK' string
}, (error) => {
console.log(error);
});
}
}
The sendTextMessage() function is called from the template by clicking an button.
Well thats it ... for me is working and hope will work for you too.
Cheers

Categories

Resources