I'm currently learning Angular, TypeScript, and RxJS. I have an HTTP request that retrieves a JSON response. Within this JSON response, there is data that I need to use to create a specific object. Let's assume that the object I want to create looks like this:
export class RegularUser {
constructor(
public id: number,
public firstName: string,
public lastName: string,
public token: string
) {}
}
Now, when I make a request to an API, the data is returned in the following format:
{
success: boolean,
uid: number,
first_name: string,
last_name: string,
cid: number,
rights: number[],
token: string
}
Since I am using the HttpClient service, my initial thought was to do the following:
this.httpClient.get(
'http://api.example.com/api/get_user'
).pipe(
tap((receivedData: Response) => console.log(receivedData)),
map((receivedData: Response) => {
return new RegularUser(
receivedData.uid,
receivedData.first_name,
receivedData.last_name,
receivedData.token);
})
);
However, in TypeScript, the receivedData
object does not contain the properties listed above. Should I create an interface for the API response and then map it to my RegularUser
object?