首页 > 解决方案 > 如何使用模型使用类或接口在角度 5 的视图中打印我的数据?

问题描述

我正在尝试打印后端返回的数据,并且我创建了一个类来分配给数据:

通过 id 获取用户的 URI 返回数据如下:

https://imgur.com/a/7QSHaaQ

和 URI 让所有用户返回数据,如下所示:

https://imgur.com/GanWAFA

我的服务中有这两个功能:

    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);
  }
}

标签: javascriptangulartypescript

解决方案


由于您正在使用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);
   })

这是一些文档和示例


推荐阅读