How do I change this function to work with the JSON change described below?
The current function returns an Observable<User[]>
, but with the new JSON, the new admin
object has been added. The new function should successfully observe both the existing users
array and the new admins
array.
getData(): Observable<User[]> {
return this.http
.get('www.example.com/api/users)
.map((r: Response) => r.json().assets.users as User[]);
}
JSON returned from /api/users
{
"assets": {
"users": [
// user objects
]
}
...now returns two arrays, users
and admins
.
{
"assets": {
"users": [
// array of user objects
],
"admins": [
// array of admin objects
]
}
Please assume that my code does have User
and Admin
classes already created that correctly reflect the properties of the related JSON objects returned.
Well, you have a few options how to return the data:
getData(): Observable<User[]> {
return this.http
.get('www.example.com/api/users')
.map((r: Response) => {
const assets = r.json().assets;
return {
users: assets.users as User[],
admins: assets.admins as Admin[]
}
});
}
Or like this:
getData(): Observable<User[]> {
return this.http
.get('www.example.com/api/users')
.map((r: Response) => {
return [
assets.users as User[],
assets.admins as Admin[]
]
});
}
Or like this:
getData(): Observable<User[]> {
return this.http
.get('www.example.com/api/users')
.map((r: Response) => {
return [
...assets.users as User[],
...assets.admins as Admin[]
]
});
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments