user5636236
user5636236

Reputation: 387

Angularjs 1.6 Component : TypeError: Cannot set property 'detailsView' of undefined

.component.js class

export var breachDetailsConfig = {
template: template,
controller: BreachDetailsComponent
};
class BreachDetailsComponent extends AutoBoundDependencies {

static get $inject() { return ['breachDetailsService', '$http']};

constructor(...dependencies) {
    super(dependencies);
}

$onInit(){
    this.detailsView = [];
    this.getBreachDetails().then(function(data){
    this.detailsView = data; // getting error here 
    });
    // this.getBreachDetails().then(function(detailsView) {
    //     this.detailsView = detailsView;
    // }); // want to use this part

}

getBreachDetails() {
    return this.$http.get('breach-mock.json').then((response) => {
         console.log(response.data);
        return response.data;
    });
}
}

ADD:

getBreachDetails() {
 //   get the breach details from JSON
    // this.breachDetailsService.getBreachDetails().then((detailsView) => {
    // this.detailsView = detailsView;
    // });
} 

what wrong here - i am trying to make a service to get the data from http call I get an error TypeError:this.breachDetailsService.getBreachDetails is not a function

I have inject the service using following:

static get $inject() { return ['breachDetailsService', '$http']};

ADD: restservice.js class

import angular from 'angular';
import breachDetailsService from './breach-details.service';
let restServiceModule = angular.module('rest-services', []);
restServiceModule.service('breachDetailsService', breachDetailsService);

This is all i have for configure, there is no controller js

export var breachDetailsConfig = {
template: template,
controller: BreachDetailsComponent
};

Upvotes: 0

Views: 252

Answers (1)

Pengyy
Pengyy

Reputation: 38191

since you are using typescript, use arrow function(ES6 new feature) to keep the context.

this.getBreachDetails().then(data => {       //  <---- arrow function here
  this.detailsView = data; // getting error here 
});

or you can bind this manually

this.getBreachDetails().then(function(data){
  this.detailsView = data; // getting error here 
}.bind(this));

Upvotes: 1

Related Questions