2017-05-24 152 views
0

.component.js的Angularjs 1.6組件:類型錯誤:無法設置屬性 '的DetailsView' 未定義

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是不是一個函數

我已經注入服務使用以下:

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

這是我的所有的配置,沒有控制器JS

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

回答

1

,因爲使用的是打字稿,使用arrow function (ES6新功能)來保持上下文。

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

,或者您也可以手動綁定this

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

謝謝!有用。 – user5636236

+0

@ user5636236現在有什麼問題?你可以在你的問題上編輯。 :) – Pengyy

+0

@ user5636236你有注入'breachDetailsS​​ervice'到你的控制器嗎?還需要發佈您的服務代碼。 – Pengyy

相關問題