Can't create alert inside onFail function of http request


#1

So I’m using the native HTTP cordova plugin for my http requests. But I can’t seem to wrap my head around a problem where I can’t create an alert inside the onFail function. Anyone else experienced this?

The error says:

Error in Error callbackId: CordovaHttpPlugin1608257770 : TypeError: Cannot
read property ‘alertCtrl’ of undefined
Here’s how I structured my code:

cordova.plugin.http.sendRequest('http://127.0.0.1:5000/api/login/', options, function(response) {

    try {   //onSuccess
        response.data = JSON.parse(response.data);

        localStorage.setItem('token', JSON.stringify(response.data.token));

      } catch(e) {
        console.error('JSON parsing error');
      }
    },  function(response) {    //onFail
        console.log('403');

        let alert = this.alerts.create({
            title: 'Error',
            subTitle: 'Username/password is invalid!',
            buttons: ['Dismiss']
        });
        alert.present();

    }
);

Here’s how my constructor looks like:

constructor(public navCtrl: NavController,
        private alerts: AlertController, 
        private http: HTTP, 
        private store: Storage, 
        ) {}

What’s causing it to not work? Been stuck for days on this. Please help


#2

function is something you pretty much never ever want to type in an Ionic function. Instead you want to utilize the fat arrows syntax, i.e. =>.

What does this mean for your code?
It means change things like:
function(response) {
to
response => { or (response) => {

(There’s no difference between the two, the latter seems to be most accepted 'round these parts but the former seems the preferred by the TypeScript style guide)


#3

Why? Angular’s HttpClient is much better I think.


#4

A comment on this, which I imagine you probably know, but the OP probably doesn’t. Parentheses are mandatory if there’s more than one parameter.

function(x,y) { return x + y }
(x, y) => x + y

But if there’s only one parameter, the parentheses can be dropped because the compiler can still compile unambiguously.

function(x) { return x }
(x) => x
x => x

However, in the case of inheritance, where you’re defining a function to be used in an expression with super for example, you might need to use parentheses for a single parameter. That gets kinda complicated, and I don’t understand it well because I avoid using inheritance in Javascript.


#5

Same here, inheritance gets kinda scary when there’s lots of stuff going on