javascript - 如何使用模型使用类或接口在角度 5 的视图中打印我的数据?
问题描述
我正在尝试打印后端返回的数据,并且我创建了一个类来分配给数据:
通过 id 获取用户的 URI 返回数据如下:
和 URI 让所有用户返回数据,如下所示:
我的服务中有这两个功能:
getUserProfile(id): Promise<void | UserProfile> {
let url = URL_SERVICIOS + '/users/' + id;
let token2 = localStorage.getItem("TOKEN");
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + token2);
let options = new RequestOptions({headers: headers});
return this.http.get(url, options)
.toPromise()
.then(response => response.json().result as UserProfile)
.catch(this.handleError);
}
getUserProfileS(sort = '-createdAt'): Promise<void | UserProfile[]> {
let url = URL_SERVICIOS + '/users/'
return this.http.get(url)
.toPromise()
.then(response => response.json() as UserProfile[])
.catch(this.handleError);
}
在我的组件中,我有下一个:
usuario:UserProfile;
this._ups.getUserProfile(id).then((user:UserProfile)=>{
alert("USUARIO"+JSON.stringify(user));
console.log(JSON.stringify(user));
this.usuario=user;
console.log(this.usuario.city);
}).catch(err=>{
console.log("ERROR"+err);
})
问题是当我在我的视图中打印时
<h1>{{usuario.name}}</h1>
它不存在,我不知道我的代码中的错误在哪里。无法读取未定义的属性“名称”
另一件事是不知道我应该使用接口还是类?
我的课是下一个:
export class UserProfile {
id: number;
photoProfile?: any;
id_facebook?: any;
name: string;
surname: string;
email: string;
password: string;
latitude: number;
longitude: number;
country_code: string;
telephone: string;
city: string;
birth: number;
photo_profile?: any;
gender: string;
who_is?: any;
roles?: any;
constructor(values: Object = {}) {
Object.assign(this, values);
}
}
解决方案
由于您正在使用promise
而不是observables
我喜欢的,
在您的服务返回promise
本身,
getUserProfile(id): Promise<void | UserProfile> {
let url = URL_SERVICIOS + '/users/' + id;
let token2 = localStorage.getItem("TOKEN");
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + token2);
let options = new RequestOptions({headers: headers});
return this.http.get(url, options).toPromise()
}
然后你可以then
在组件中使用并使用user.result
使用,this.usuario = user.result;
而不是如果this.usuario=user;
this._ups.getUserProfile(id).then((user:UserProfile)=>{
alert("USUARIO"+JSON.stringify(user));
console.log(JSON.stringify(user));
this.usuario=user.result;
console.log(this.usuario.city);
}).catch(err=>{
console.log("ERROR"+err);
})
推荐阅读
- asp.net-core - SignalR,如何确保一次只有一个用户可以编辑给定的表单?
- c++ - 如何在 gcc/g++ 中指定尖括号标头的位置?
- html - 如何使用 CSS 隐藏某些文本?
- image - 如何获取 Image 组件内显示内容的实际大小(包含模式)?
- java - 查找出现在大写和小写中的最大字母
- winapi - InvalidateRect() 是否足以要求系统重绘静态控件背景?
- c - 多次调用后从 strtok 存储指针字符的运行时错误
- reactjs - 如何使用 useState?我究竟做错了什么?
- php - 更改已在其他文件中设置的页面的标题
- python - 根据另一个数据框中列的 if 语句填充数据框中的列 - Python