For my Uni project, I need to create an application where I call on data from a server. The URL requires specific 'project ID's'. What I need to do is somehow count the project data from 0 to 20 to find out which project ID's match.
This is what I've got so far. I've tried to replace ' 1 ' with a variable, and count up from that with a for/while loop but that doesn't want to work. Any ideas would be helpful!
$scope.projectList = [];
$http.get('https://happybuildings.sim.vuw.ac.nz/api/sooleandr/project.' 1 '.json').then(
function successCall(response){
$scope.projectList.push(response.data);
}
this is also another thing I've done, it's still not getting my data though but it doesn't break my code
$scope.projectList = [];
var id = 0;
var targetURL = 'https://happybuildings.sim.vuw.ac.nz/api/sooleandr/project.' id '.json';
$http.get(targetURL).then(
function successCall(response){
while(id<20){
$scope.projectList.push(response.data);
id ;
}
}
)
CodePudding user response:
You seem to have a bit of a misunderstanding on how and when the values of variables are calculated in JavaScript. When you declare a variable and set its value, it calculates the expression and stores it at that specific time. In this context, targetURL
is no longer evaluated with the concatenation of id
once it's initially set - it's just a simple string.
Move the logic around in your script such that the variable is calculated on every iteration of id
:
$scope.projectList = [];
var id = 0;
while (id < 20) {
var targetURL = 'https://happybuildings.sim.vuw.ac.nz/api/sooleandr/project.' id '.json';
$http.get(targetURL).then(
function successCall(response){
$scope.projectList.push(response.data);
}
);
id ;
}
If you're interested in a slightly more succinct alternative, you really don't even have to declare id
in the broader scope or increment it within your loop if you use a more C-style for
:
$scope.projectList = [];
for (var id = 0; id < 20; id ) {
var targetURL = 'https://happybuildings.sim.vuw.ac.nz/api/sooleandr/project.' id '.json';
$http.get(targetURL).then(
function successCall(response){
$scope.projectList.push(response.data);
}
);
}
If the execution flow of JavaScript is confusing for you, I'd recommend seeking out some fundamental literature on how variables work and how loops affect the execution of your code in JavaScript, as this is quite a fundamental tenet of the language and will pay dividends as you begin to take on requirements with greater and greater complexity in logic.