Angularjs 1.6组件:TypeError:无法设置属性' detailsView'未定义的

时间:2017-05-24 14:42:22

标签: javascript angularjs

.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;
    // });
} 

这里有什么不对 - 我正在尝试提供服务以从http调用中获取数据我得到一个错误TypeError:this.breachDetailsS​​ervice.getBreachDetails不是函数

我使用以下内容注入服务:

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

ADD: restservice.js类

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

这就是我所拥有的所有配置,没有控制器js

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

1 个答案:

答案 0 :(得分:1)

因为你正在使用打字稿,所以使用this.getBreachDetails().then(data => { // <---- arrow function here this.detailsView = data; // getting error here }); (ES6新功能)来保持上下文。

this

或者您可以手动绑定this.getBreachDetails().then(function(data){ this.detailsView = data; // getting error here }.bind(this));

form