Alex Brend Alex Brend - 4 months ago 28
AngularJS Question

this is undefined in angularjs fullstack MEAN. when using with interval

If i am using this.$onInit(); from other function its working.
but if make call with function it gives an this is undefined error.

I'm new in angularjs. Please help me to solve this issue.

class ChatComponent {

constructor($http, $scope, socket, Auth, $interval) {
this.$http = $http;
this.socket = socket;
this.users = [];
this.setView = false;
this.suggestionResponse = {};
this.$interval = $interval;
this.activeConversion = {};


this.currentUser = Auth.getCurrentUser()._id;
console.log(this.currentUser);


$interval(function() { this.$onInit; },10000);


}

$onInit() {
this.$http.post('/api/conversions/getconversation', {
userId: this.currentUser
}).then(response => {
var conversionArray = response.data[0].conversions;
for(var i=0; i < conversionArray.length; i++){

var metch = this.mergeArray(conversionArray[i]._id, response.data[0].messages);
if(metch){
conversionArray[i].message = metch;
}
else{
conversionArray[i].message = [];
}

}
this.users = conversionArray;

});
}

}



}


$onInit method simple fetch last messages of conversions.

Answer

On the top of the controller;

var self = this;

So self is always refers to the your constructor and in the $onInit() you ca use as

self.users = conversionArray