erichardson30 erichardson30 - 3 months ago 18
AngularJS Question

Angular function in controller not getting called after promise

I am building an Angular 1.5 app using the component structure. After the promise comes back from the $http call in the service, I am trying to call another function to filter the dataset before it is displayed on the UI.

However, the filterApps function is not getting called.

Also...in the filterApps function I am trying to compare to arrays of objects and return back the ones that have the same name. Is this the best way to go about this or is there a cleaner way?

Controller :

import allApps from '../../resources/data/application_data.js';

class HomeController {
/*@ngInject*/
constructor(ItemsService) {
this.itemsService = ItemsService;
this.displayApps = [];
}

$onInit() {
this.itemsService
.getItems()
.success((apps) => this.filterApps(apps));
}

filterApps(siteApps) {
this.displayApps = allApps.applications.filter((app) => {
siteApps.applications.map((siteApp) => {
if(siteApp.name === app.name) {
return app;
}
})
});
}
}

export default HomeController;

Answer

I don't see any reason that filterApps method isn't geting call(as you already commented that success function is getting called). I guess you're just checking nothing has been carried in displayApps variable. The real problem is you have not return internal map function result to filter. So that's why nothing gets return.

Code

filterApps(siteApps) {
    this.displayApps = allApps.applications.filter((app) => {
        //returning map function result.
        return siteApps.applications.map((siteApp) => {
            if(siteApp.name === app.name) {
                return app;
            }
        })
    });
}
Comments