cancel
Showing results for 
Search instead for 
Did you mean: 

Magento 2.2: Ajax call not working when being called during initialization

Magento 2.2: Ajax call not working when being called during initialization

I have created a custom page where customer accounts that belong to the same company are listed.

The table content is based on an observable array so that it updates automatically when an account is edited or added.

For testing purposes I added a click binding to the table header. When I click on the header everything works properly.

Then I added the getUser function to the initialize method so that the table is populated when the page is rendered. But then the function that worked properly all the sudden returns an error: response.forEach is not a function. I added console.log(response); It surprisingly returns html code (the first 20 lines of the page). What am I doing wrong?

 

define([
    'ko',
    'uiComponent',
    'mage/url',
    'mage/storage',
    ],
    function (ko, Component, urlBuilder, storage) 
    {   
        'use strict';
        return Component.extend({            defaults: {template: 'Test_Account/userlist',},            userList: ko.observableArray([]),            errorMessage : ko.observable(),
            /** @inheritdoc */            initialize: function () {
                this._super();
                this.getUser();
                return this;
            },            getUser: function () {
                var self = this;
                var serviceUrl = urlBuilder.build('account/useraccounts/user');
                return storage.post(serviceUrl,''
                ).done(function (response) {
                    self.userList.removeAll();                    console.log("Test");                    console.log(response);                    response.forEach(function(element) {
                        self.userList.push(element);
                    });
                }
                ).fail(function (response) {
                    self.errorMessage = response;});
            },
        });
    }
);