In my development project, I have an Angular component and controller set up in the following way:
export class MyController{
static $inject = [MyService.serviceId];
public elements: Array<string>;
public errorReceived : boolean;
private elementsService: MyService;
constructor(private $elementsService: MyService) {
this.errorReceived = false;
this.elementsService= $elementsService;
}
public $onInit = () => {
this.elements = this.getElements();
console.log("tiles: " + this.elements);
}
private getElements(): Array<string> {
let result: Array<string> = [];
this.elementsService.getElements().then((response) => {
result = response.data;
console.log(result);
}).catch(() => {
this.errorReceived = true;
});
console.log(result);
return result;
}
}
export class MyComponent implements ng.IComponentOptions {
static componentId = 'myId';
controller = MyController;
controllerAs = 'vm';
templateUrl = $partial => $partial.getPath('site.html');
}
The implementation of MyService is as follows:
export class MyService {
static serviceId = 'myService';
private http: ng.IHttpService;
constructor(private $http: ng.IHttpService) {
this.http = $http;
}
public getElements(): ng.IPromise<{}> {
return this.http.get('./rest/elements');
}
}
An issue that has arisen is that the array 'elements' remains empty after the invocation of onInit(). Nonetheless, data has been received as the success function in getELements() logs the elements to the console.
In my template, I use the 'elements' array to determine whether to display a specific element. Here's how it's done:
<div>
<elements ng-show="vm.elements.indexOf('A') != -1"></elements>
</div>
The challenge now is that 'vm.elements' initially holds an empty array, and only later does it receive the actual values. By then, the expression in the template has already been evaluated. What adjustments can be made to address this?