登录需跳转页面,出现「无法获取未定义/空引用的push属性」错误求助
Hey there, let's break down exactly what's causing this error and get your login page redirect working properly.
The Root of the Problem
That error pops up for two key reasons:
- Lost
thiscontext: Inside jQuery's.done()callback function, the value ofthisdoesn't point to your Ionic/Angular component instance anymore—it refers to the jQuery XHR request object instead. Sothis.navCtrlisundefined, hence the "push property not found" error. - Potential incorrect page reference:
TabsPage[0]looks suspicious. Normally,navCtrl.push()expects you to pass the page component itself, not an index from an array (unless you specifically stored your page components in an array calledTabsPage, which isn't standard).
Quick Fixes
Here are two straightforward ways to resolve the context issue, plus a correction for the page navigation:
Option 1: Use Arrow Functions (Recommended)
Arrow functions inherit the this context from their surrounding scope, so they'll keep pointing to your component instance:
Accesso(){ $.get("http://localhost:4000/utente?matricola="+this.username+"&password="+this.pass) .done((data) => { // Arrow function preserves component's `this` if(data=="Errore"){ alert("Errore"); } else { alert("success - "+data); this.navCtrl.push(TabsPage); // Pass the actual page component } }) .fail((data) => { alert("error- " + data); }); }
Option 2: Save this to a Variable
If you prefer not to use arrow functions, store the component's this in a variable before the AJAX call:
Accesso(){ const self = this; // Save component context to `self` $.get("http://localhost:4000/utente?matricola="+this.username+"&password="+this.pass) .done(function(data){ if(data=="Errore"){ alert("Errore"); } else { alert("success - "+data); self.navCtrl.push(TabsPage); // Use `self` instead of `this` } }) .fail(function(data){ alert("error- " + data); }); }
Bonus: Better Practice with Angular's HttpClient
Since you're using Ionic/Angular, it's better to ditch jQuery's AJAX and use Angular's built-in HttpClient—it plays nicer with the framework and avoids context headaches by default. Here's how that would look:
// First, inject HttpClient and NavController in your component constructor constructor(private http: HttpClient, private navCtrl: NavController) {} Accesso(){ const url = `http://localhost:4000/utente?matricola=${this.username}&password=${this.pass}`; this.http.get(url).subscribe( (data: any) => { if(data === "Errore"){ alert("Errore"); } else { alert("success - "+data); this.navCtrl.push(TabsPage); } }, (error) => { alert("error- " + error); } ); }
Note on TabsPage[0]
If you did intentionally store your page components in an array called TabsPage, then TabsPage[0] is fine—just make sure that array is properly defined and contains valid component references. Otherwise, stick to passing TabsPage directly.
内容的提问来源于stack exchange,提问作者lorenzo grosso

