0

I have a form in my page. When a user clicks a button if have no problem this code must navigate my Tile page. I am taking this problem:Uncaught TypeError: Cannot read property 'navTo' of undefined.

This my code:

 onPressGonder: function (evt) {
  var sURL = "xxxxxx";
  $.ajax({  
    url: sURL,  
    dataType: "json",
    success: function(data) {
      if (data.ResultCode === 7) {
        sap.m.MessageToast.show("Error:" +data.Alerts[0].Message+"") ; 
      } else {
        sap.m.MessageToast.show("Login succesfull.");
        sap.ui.core.UIComponent.getRouterFor(this).navTo("Tile");
      }   
    }
  }); 
}  
cschuff
  • 5,502
  • 7
  • 36
  • 52
Emre
  • 153
  • 2
  • 3
  • 16

1 Answers1

0

You are having a scope problem. The function provided as a success callback is a anonymous function called later on by jQuery.ajax. Therefore it is NOT a method of your controller and thereby does not know this. By default (as in your anonymous function) this refers to the window object. So what your basically doing is:

sap.ui.core.UIComponent.getRouterFor(window).navTo("Tile");

And the window object obviously does not have a router or a navTo method ;) The easiest workaround is to make this available via the closure scope as follows:

onPressGonder: function (evt) {
  var sURL = "xxxxxx",
      that = this;
  $.ajax({  
    url: sURL,  
    dataType: "json",
    success: function(data) {
      if (data.ResultCode === 7) {
        sap.m.MessageToast.show("Error:" +data.Alerts[0].Message+"") ; 
      } else {
        sap.m.MessageToast.show("Login succesfull.");
        sap.ui.core.UIComponent.getRouterFor(that).navTo("Tile");
      }   
    }
  }); 
}

Another probably more elegant solution is to use the context property of jQuery.ajax. It will ensure that any ajax callback will be executed with the provided context (meaning whatever you pass as a context will be referred to as this inside your callbacks):

  $.ajax({  
    ...
    success: function(data) {
      ...
      sap.ui.core.UIComponent.getRouterFor(this).navTo("Tile"); 
    },
    context: this
  }); 
Community
  • 1
  • 1
cschuff
  • 5,502
  • 7
  • 36
  • 52