Reputation: 512
I am using RxJS Ajax() to return a bunch of GitHub users. I want to iterate over each one and just get the login
names from each user. I am able to iterate over a local array of objects, but not if that array of objects came from Ajax, whether or not I force it to be a stream with RxJS from()
.
// from() the array of objects (locally defined)
let localArrayOfObj = from([
{ login: 'Barbara Holland', loggedIn: false, token: null },
{ login: 'Joyce Byers', loggedIn: true, token: 'abc' },
{ login: 'Nancy Wheeler', loggedIn: true, token: '123' }
]);
// Return the "login" names:
localArrayOfObj.pipe(
map((data) => data.login)
).subscribe(console.log); // This returns the login names
// from() the array of objects (returned by Ajax)
const githubUsers = `https://api.github.com/users?per_page=2`;
const arrayFromAjax = from(ajax.getJSON(githubUsers));
arrayFromAjax.subscribe(console.log);
// Trying the same to return the "login" names:
arrayFromAjax.pipe(
map((data) => data.login)
).subscribe(console.log); // This is undefined
I'm putting the results of the Ajax call through RxJS from()
so both arrays are treated the same, however the same undefined
results occur if I skip from()
and just do
const arrayFromAjax = ajax.getJSON(githubUsers);
instead of
const arrayFromAjax = from(ajax.getJSON(githubUsers));
How is an array of objects from Ajax() different than a similar locally defined array of objects? And how can I iterate over the Ajax results?
Upvotes: 1
Views: 206
Reputation: 14740
The from()
operator creates an observable that emits the provided values one at at time, so you are not receiving an array, you are receiving individual objects.
ajax.getJSON(githubUsers)
returns an array of objects. This is why you are seeing differences between these two cases.
You can alter your test case with local array to the following the match the same shape:
let localArrayOfObj = from([
[
{ login: 'Barbara Holland', loggedIn: false, token: null },
{ login: 'Joyce Byers', loggedIn: true, token: 'abc' },
{ login: 'Nancy Wheeler', loggedIn: true, token: '123' }
]
]);
In your code here: data
is an array, so if you want to modify the elements individually you can do something like:
arrayFromAjax.pipe(
map((dataArray) => dataArray.map(data => data.login))
).subscribe(console.log); // This is undefined
Upvotes: 1