问题
I get this error
Uncaught TypeError: Cannot read property 'element' of undefined
when I press on login button in my ionic2 and angular2 app. I tried to look on variable that not intialize or function but I didn't find at all.
that's the login function
import { Component } from '@angular/core';
import { NavController,ViewController } from 'ionic-angular';
import { Storage} from '@ionic/storage';
//components
import { MyService } from '../../providers/my-service';
import { AdminPage } from '../admin/admin';
/*
Generated class for the ModalPage page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
@Component({
selector: 'page-modal-page',
templateUrl: 'modal-page.html',
providers:[MyService]
})
export class ModalPage {
data:any;
public local: Storage;
private mydata:any;
constructor(public navCtrl: NavController,private viewCtrl: ViewController,private service:MyService) {
this.data={};
this.data.username="";
this.data.password="";
this.local=new Storage();
}
login(){
let username = this.data.username;
let password = this.data.password;
let data = JSON.stringify({username, password});
this.service.postLogin(data)
.subscribe(data => {
this.mydata = data;
this.local.set('username', this.mydata[0].name);
this.local.set('token', this.mydata[0].token);
this.viewCtrl.dismiss();
}, error =>{
console.log(error);
})
}
dismiss(){
this.viewCtrl.dismiss();
}
}
this is my-service page
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Storage} from '@ionic/storage';
import {NavController} from "ionic-angular";
import { AdminPage } from '../pages/admin/admin';
/*
Generated class for the MyService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class MyService {
public local:Storage;
private mydata:any;
public getsession: any;
constructor(public http: Http,private local: Storage,private navCtrl:NavController) {
this.local=new Storage();
}
postLogin(data){
let link = "http://adirzoari.16mb.com/newapi.php";
return this.http.post(link,data)
.map(res => res.json())
}
checkToken(){
return this.getsession =this.local.get('token');
}
}
回答1:
Seems like you access a field 'elementsomewhere in the templatemodal-page.html`. For example,
{{ something.element }}
If so, try {{ something?.element }} instead.
This check if something exists (not null or undefined) before accessing a field.
来源:https://stackoverflow.com/questions/39856720/uncaught-typeerror-cannot-read-property-element-of-undefined-when-press-login