Ionic native HTTP catch is null - ionic-framework

I am playing around with Ionic and would like to make an API call to a REST API that I wrote in ASP .NET Core. Now I know the API works 100% as I am able to use Postman to call it and it works without issue.
However when I try to call the API from Ionic using the native http client I am getting a weird error. The catch of the promise is being triggered but there is no error. The code I am using is as follows:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { HTTP } from '#ionic-native/http';
#Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [HTTP]
})
export class HomePage {
credentialsForm: FormGroup;
constructor(public navCtrl: NavController,
private formBuilder: FormBuilder,
private http: HTTP) {
this.credentialsForm = this.formBuilder.group({
email: ['', Validators.required],
password: ['', Validators.required]
});
}
onLogin() {
let endpoint = "https://api.mywebsite.mytld/api/vi/";
var data = {
"emailAddress": this.credentialsForm.controls['email'].value,
"password": this.credentialsForm.controls['password'].value
}
this.http.post('https://api.mywebsite.mytld/api/vi/token', JSON.stringify(data), {headers : {'Content-Type' : 'application/json'}})
.then(data => {
console.log('Success');
})
.catch(error => {
console.log('Failure');
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
}
}
The output I am getting in the console is the following:
[app-scripts] [12:57:50] console.log: Failure
[app-scripts] [12:57:50] console.log: null
[app-scripts] [12:57:50] console.log: null
[app-scripts] [12:57:50] console.log: null
Do you possibly have any idea why this is happening?

Related

setting global variable in ipcRenderer.on eventhandler running ionic on electron does not work

This is my code in home.ts to receive values from main-process
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
declare var electron : any;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
arguments: any="ping";
constructor(public navCtrl: NavController) {
}
ionViewDidLoad() {
electron.ipcRenderer.send("test_channel","ping");
electron.ipcRenderer.on("test_channel", function (err,arg) {
this.arguments=arg; // receive new value "pong" from main.js
console.log("Message received from electron: "+arg); // works fine
});
console.log("Message received from electron: "+this.arguments); //does not work, still default value
};
}
This is added in my code in main.js, and it works to receive the event from render-process
var ipcMain = require('electron').ipcMain;
mainWindow.webContents.openDevTools();
ipcMain.on("test_channel",function(err,arg){
console.log(err);
console.log("Received message: "+arg);
global.sharedObj = {prop1: arg};
console.log("Sending message back!");
// Send message back!
mainWindow.webContents.send("test_channel",arg+'yeah');
})
This is added in my index.html, to make it run for ionic
<script>
const electron = require('electron');
</script>
First of all don't duplicate the message name. and in the main.js , send the event request to the renderer process using event.sender.send as shown below:-
ipcMain.on('message_name', (event,args) => {
event.sender.send('message_name_2', args)
});

Use property as form validator in Angular2 (data-driven)

I'm having a hard time trying to set a max value using the data driven approach in Angular2.
I want to set the max value of the input to a property called userLimit, which I get from firebase. This is my code:
component.ts
import { Component, OnInit, AfterViewInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from "#angular/forms";
import { FiredbService } from '../services/firedb.service';
import { AuthService } from '../services/auth.service';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
#Component({
selector: 'my-dashboard',
styleUrls: ['./recibirpago.component.scss'],
templateUrl: './recibirpago.component.html'
})
export class RecibirpagoComponent implements OnInit, AfterViewInit {
myForm2: FormGroup;
uid: string;
userLimit: any;
constructor(private fb: FormBuilder,
private dbfr: FiredbService,
private db: AngularFireDatabase,
private authService: AuthService) {
this.myForm2 = this.fb.group({
email: ['', Validators.email],
clpmount: ['', [Validators.required, Validators.max(this.userLimit)]]
});
}
ngOnInit() {
this.uid = this.authService.getUserUid();
}
ngAfterViewInit() {
this.dbfr.getUserLimit(this.uid).subscribe(snapshot => {
this.userLimit = snapshot.val().accountLimit;
console.log(this.userLimit);
})
}
If I write, for example, Validators.max(5000) it works, but if I try to get the data from Firebase it doesn't work.
Thanks for your help!
The problem is that the constructor is executing before the ngAfterViewInit so you don't have the value of the userLimit at that point.
Instead use the setVAlidators method within the subscribe where you get the data.
Something like this:
constructor
this.myForm2 = this.fb.group({
email: ['', Validators.email],
clpmount: ['', Validators.required] // <-- not here
});
ngAfterViewInit
ngAfterViewInit() {
this.dbfr.getUserLimit(this.uid).subscribe(snapshot => {
this.userLimit = snapshot.val().accountLimit;
console.log(this.userLimit);
const clpControl = this.myForm2.get(`clpmount');
clpControl.setValidators(Validators.max(this.userLimit)); // <-- HERE
clpControl.updateValueAndValidity();
})
}
NOTE: Syntax was not checked.

Angular2 appear warning XMLHttpRequest at chrome

I used Http Restful API at Angular2, but appear the following warning message.
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
Please tell me how to do that.
http_restful_service.ts
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class HTTPRestfulService {
constructor(private _http: Http) {}
getAllProjectName() {
var headers = new Headers();
headers.append('Content-Type','charset=uft-8');
return
this._http.get('http://localhost/api/database/',
{headers: headers})
.map(res => res.json());
}
}
backstage_view.component.ts
import { Component, OnInit } from '#angular/core';
import { HTTPRestfulService } from './../../../service/http_restful_service';
#Component({
moduleId: module.id,
selector: 'backstage_view',
templateUrl: './backstage_view.component.html',
styleUrls: ['./backstage_view.component.css']
})
export class BackstageViewComponent implements OnInit {
allProjects: string;
constructor(private _restfulapi: HTTPRestfulService) {}
ngOnInit() {
this._restfulapi.getAllProjectName()
.subscribe(
data => this.allProjects = data,
error => console.log(error),
);
}
}
Why can't you pass the content-type as 'application/json' format,
let url= `http://localhost/api/database/`;
let headers = new Headers();
headers.append('Content-Type','application/json');
let params = new URLSearchParams;
params.append('id', id);
params.append('user_id', user_id);
return this.authHttp.post( url, { headers:headers, search:params })
.map(res => res.json());

Angular2: strange vague error when trying to get Json from server using a rest service

I am trying to get a product from a local server using an angular2 rest service. When I do the GET I get the following error. I can get the item from the server using the Insomnia rest client so I know the issue is not with the server. i've also checked the url and made sure there's no errors there. Any idea what else I can check? i'm using ng-cli to run the app...
my error:
http://10.60.160.34/BRMServices/WebEnquiry//POSEnquiry/293
Failed to load resource: net::ERR_CONNECTION_RESET
app.component.ts:32
failureServer error
my rest service:
import { Injectable } from '#angular/core';
import { Http, Headers, Response, RequestOptions } from "#angular/http";
import { Observable } from "rxjs/Rx";
import { ProductModel } from "../models/product.model";
//import 'rxjs/add/operator/map';
//import 'rxjs/add/operator/catch';
//import 'rxjs/add/observable/throw'
#Injectable()
export class RestService {
public API_URL: string = "http://10.60.160.34/BRMServices/WebEnquiry/";
private headers: Headers;
private options: RequestOptions;
constructor(private http: Http){
this.init();
}
init() {
this.headers = new Headers({ 'Content-Type': 'application/json' });
this.options = new RequestOptions({ headers: this.headers });
}
getProduct(barcode: string): Observable<ProductModel> {
return this.http.get(this.API_URL + "/POSEnquiry/" + barcode, this.options)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
}
my app.component.ts:
import { Component } from '#angular/core';
import { RestService } from "./services/rest.service";
import { ProductModel } from "./models/product.model";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
product: ProductModel;
constructor(private restService: RestService){}
submitBarcode(barcode: HTMLInputElement){
this.restService.getProduct(barcode.value)
.subscribe((res) => {
//product = res;
console.log(res);
}, (res) => {
console.log("failure" + res);
});
//console.log("product: " + product);
}
}
It turned out to be the RequestOptions variable. When I replaced options with headers in the get request it worked with no issues...

How to perform async validation using reactive/model-driven forms in Angular 2

I have an email input and I want to create a validator to check, through an API, if the entered email it's already in the database.
So, I have:
A validator directive
import { Directive, forwardRef } from '#angular/core';
import { Http } from '#angular/http';
import { NG_ASYNC_VALIDATORS, FormControl } from '#angular/forms';
export function validateExistentEmailFactory(http: Http) {
return (c: FormControl) => {
return new Promise((resolve, reject) => {
let observable: any = http.get('/api/check?email=' + c.value).map((response) => {
return response.json().account_exists;
});
observable.subscribe(exist => {
if (exist) {
resolve({ existentEmail: true });
} else {
resolve(null);
}
});
});
};
}
#Directive({
selector: '[validateExistentEmail][ngModel],[validateExistentEmail][formControl]',
providers: [
Http,
{ provide: NG_ASYNC_VALIDATORS, useExisting: forwardRef(() => ExistentEmailValidator), multi: true },
],
})
export class ExistentEmailValidator {
private validator: Function;
constructor(
private http: Http
) {
this.validator = validateExistentEmailFactory(http);
}
public validate(c: FormControl) {
return this.validator(c);
}
}
A component
import { Component } from '#angular/core';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import { ExistentEmailValidator } from '../../directives/existent-email-validator';
#Component({
selector: 'user-account',
template: require<string>('./user-account.component.html'),
})
export class UserAccountComponent {
private registrationForm: FormGroup;
private registrationFormBuilder: FormBuilder;
private existentEmailValidator: ExistentEmailValidator;
constructor(
registrationFormBuilder: FormBuilder,
existentEmailValidator: ExistentEmailValidator
) {
this.registrationFormBuilder = registrationFormBuilder;
this.existentEmailValidator = existentEmailValidator;
this.initRegistrationForm();
}
private initRegistrationForm() {
this.registrationForm = this.registrationFormBuilder.group({
email: ['', [this.existentEmailValidator]],
});
}
}
And a template
<form novalidate [formGroup]="registrationForm">
<input type="text" [formControl]="registrationForm.controls.email" name="registration_email" />
</form>
A've made other validator this way (without the async part) and works well. I think te problem it's related with the promise. I'm pretty sure the code inside observable.subscribe it's running fine.
What am I missing?
I'm using angular v2.1
Pretty sure your problem is this line:
...
email: ['', [this.existentEmailValidator]],
...
You're passing your async validator to the synchronous validators array, I think the way it should be is this:
...
email: ['', [], [this.existentEmailValidator]],
...
It would probably be more obvious if you'd use the new FormGroup(...) syntax instead of FormBuilder.