I've been developing an Angular 2 app (RC5) with a NodeJS backend RESTful API integration.
One specific route on the backend returns an array of 'Candidates':
exports.list = function (req, res, next) {
const sort = req.query.sort || null
const fields = req.query.fields || null
let query = Candidate.find()
if (sort !== null) {
query.sort(sort.replace(',', ' '))
}
if (fields !== null) {
query.select(Candidate.reduceFields(fields))
}
query
.then(function (candidates) {
res.send(candidates)
})
.catch(next)
}
In the frontend service, I fetch this data like so:
getCandidates() {
return this.http
.get(`http://localhost:3500/api/v1/proboard/candidates`)
.map(function (res) {
console.log("First:" + res.json());
return res.json();
})
};
When the controller subscribes to this observable:
ngOnInit() {
this.subscription = this.candidateService.getCandidates()
.subscribe(
(candidates: Candidate[]) => {
console.debug("Got:" + JSON.stringify(candidates));
this.candidates = candidates;
}
);
}
It works as intended in terms of retrieving the data. However, the issue is that the controller receives an array of objects from the stream, not individual elements as desired.
For instance, if there are 20 candidates returned, the subscription code only runs once and the controller gets an array of 20 elements altogether.
What I actually aim for is the subscription code to run 20 times, each time with a single element instead of receiving the entire array at once.
I realize that my understanding of how RxJs operates is lacking. How should I modify this code so that the controller fetches one element at a time rather than the entire array simultaneously?
The reason behind this modification is because I ultimately want to receive updates to the candidate list while the controller is active, not just the initial list.