For example this is the json which I am receiving,
{
"events": [...
],
"total": 12341,
"students": [
{
"id": 1,
"first_name": "John",
"last_name": "Apple"
},
{
"id": 2,
"first_name": "Bob",
"last_name": "Banana"
},
{
"id": 3,
"first_name": "Charles",
"last_name": "Carrot"
}
]
}
And I want to transform the data to the following form, and return it as an observable
[
{
"first_name": "John",
"last_name": "Apple"
},
{
"first_name": "Bob",
"last_name": "Banana"
},
{
"first_name": "Charles",
"last_name": "Carrot"
}
]
I have tried the following, but it returns undefined.
getStudentsName(): Observable<any> {
const requestUrl = this.rootURL + `students/`;
let studentsInfo = this.http.get<any>(requestUrl).pipe(map(o => o.students));
return studentsInfo.pipe(map(students => {students.first_name, students.last_name}));
}
returns undefined when subscribing to observable
this.getStudentsInfoService.getStudentsName()
.subscribe((result) => console.log('here', result));
The Problem
The Problem is with your how you return your observable
Lets break the code down
In the above
studentsInfo
will be of typeObservable<any>
Next line is as per below
Lets have a look at the below section
This part of the section actually has no return statement hence by default javascript returns undefined!
Solution
To use arrow function without a return statement, you will need to wrap
{}
inside a()
like belowBelow will work