I am facing an issue while trying to display the data fetched from my backend. I have created a class to handle the data:
When I request the User by ID URI, the returned data looks like this:
https://i.sstatic.net/76BSY.jpg
Similarly, when I request all Users using another URI, the data is returned in the following format:
https://i.sstatic.net/5Aetm.jpg
I have implemented two functions in my service:
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);
}
In my component, I have the following code:
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);
})
The problem arises when I try to display the user's name in my view:
<h1>{{usuario.name}}</h1>
I receive an error message stating "Cannot read property 'name' of undefined", and I cannot pinpoint the error in my code.
Furthermore, I'm unsure whether I should be using interfaces or classes for this purpose.
The structure of my class 'UserProfile' is as follows:
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);
}
}