Reputation: 154
I am trying to create several resources with a single function.
Right now I have this function:
getResource(id) {
let url = this.databaseURL + 'rest/resource/' + id;
return this.http.get(url)
.map(res => res);
}
and then in the class I start the resources:
resource1 = [];
resource2 = [];
and in the constructor I make the calls:
this.getResource('resource1')
.subscribe(data => {
this.resource1 = data;
}
}
});
this.getResource('resource2')
.subscribe(data => {
this.resource2 = data;
}
}
});
As you can see it is repeating code (and I have to call a lot of resources.) I do not know if you could do something like create the function
this.getResources(arrayResources)
.subscribe(data => {
this.resource1 = data;
}
}
});
and in the constructor
arrayResources = ['resource1', 'resource2']
this.getResources(arrayResources)
But as you have to subscribe to that getResources and also the resources are not defined in the class I'm losing a bit and I do not know how I could do it ... do you think of one?
Upvotes: 1
Views: 242
Reputation: 92447
May be something like this (i make code from head):
this.arrayResources = new Array(10);
for(i=0; i<this.arrayResources.length; i++)
{
this.getResource('resource'+i)
.subscribe(data => {
this.arrayResources[i] = data;
}
}
});
}
I not use separate array for resources names however it is easy to introduce and put into for loop.
Upvotes: 1