gpt4 book ai didi

javascript - Angularjs 1.6组件: TypeError: Cannot set property 'detailsView' of undefined

转载 作者:行者123 更新时间:2023-12-03 04:15:23 27 4
gpt4 key购买 nike

.component.js

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

添加:

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

这里出了什么问题 - 我正在尝试创建一个服务来从 http 调用获取数据,但出现错误 TypeError:this.breachDetailsS​​ervice.getBreachDetails 不是函数

我已使用以下方式注入(inject)服务:

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

添加:Restservice.js 类

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

这就是我所有的配置,没有 Controller js

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

最佳答案

由于您使用的是 typescript ,因此请使用箭头函数(ES6新功能)来保留上下文。

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

或者您可以手动绑定(bind)this

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

关于javascript - Angularjs 1.6组件: TypeError: Cannot set property 'detailsView' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44161696/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com