我对 ionic 2 有一个非常问题,我正在获取一个 JSON 对象,我可以使用代码<span>{{ user|json }}</span>
检查对象数据是否存在,但是当我使用代码时<span>{{ user.id }}</span>
会显示异常,并显示消息"无法读取 null 的属性 ID"。this.userService.get( this.user_id )
方法用于另一个部分,工作正常,但在本节中没有,你能帮我吗?
这是我的代码:
<!-- my profile.html view -->
<ion-row>
<ion-col col-4>
Tipo de socio
</ion-col>
<ion-col col-8>
<span>{{ user.id }}</span><!-- cannot read id property of a null -->
</ion-col>
</ion-row>
<ion-row>
<ion-col col-4>
Tipo de socio
</ion-col>
<ion-col col-8>
<span>{{ user|json }}</span><!-- the data is returned -->
</ion-col>
</ion-row>
// My profile.ts ( where I'm loading the view and calling the user services )
import { User, UserService } from '../../app/models/user';
@Component({
selector: 'page-profile',
templateUrl: 'profile.html'
})
export class ProfilePage {
title = 'My Profile';
user: User = null;
private user_id: number = 0;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public alertCtrl: AlertController,
public modalCtrl: ModalController,
public loadingCtrl: LoadingController,
public userService: UserService) {
this.user_id = this.navParams.get('user_id'); // this value is working fine!
if ( this.user_id > 0 ) {
this.userService.get( this.user_id ).then( user => this.user = user );
}
}
ionViewDidLoad() { }
}
// My user.ts ( where I've my services )
@Injectable()
export class User {
id: number;
name: string;
email: string;
ic: number;
birth_date: string;
home_phone: number;
phone: number;
is_active: boolean;
is_admin: boolean;
from_social_account: boolean;
is_superuser: boolean;
status: boolean;
created_at: any;
updated_at: any;
groups: any;
permissions: any;
addresses: any;
all_permissions: any;
auth_token: string;
is_customer: boolean;
is_partner: boolean;
last_login: string;
profile: any;
requests: any;
skills: any;
social_providers: any;
wallets: any;
errors: any = null;
birth_date_no_formatted: string;
main_address: any;
}
@Injectable()
export class UserService {
private headers: Headers = new Headers(Constant.DEFAULT_HEADERS);
private url: string = `${Constant.API_HOST}${Constant.API_PREFIX}${Constant.API_V1}`;
constructor(
private http: Http) { }
get( _id: number ): Promise<User> {
let url = `${this.url}users/${_id}/`;
return this.http.get(url, { headers: this.headers })
.toPromise().then( response => response.json() as User ).catch(this.handleError);
}
private handleError(error: any): any {
console.log( JSON.stringify( error ) );
return {errors: StaticMethods.formatSubmitErrors( error.json() ) };
}
}
您的代码实际上有效,但尝试显示空值,直到返回承诺数据。
要解决此问题,您可以使用如下safe-navigation operator
:
{{ user?.id }}
因此,仅当用户不为 null 时,才会读取 id 和其他内容。