我正在开发一个使用Babel和Angular 1.5.0的角度fullstack项目。
问题在于,当我构建一个数组(this.events = [])时,我无法在$ onInit()上定位这个数组,我应该填充要在ui-calendar上显示的数据。我在this.awesomeTesting = [];
上这样做所以我需要在$ onInit()中使用来自$ http.get('/ api / calendars /')的数据填充this.events []数组,但是我不明白为什么我无法定位数组所以我可以填充数据。
我做错了什么?
这是我的代码:
'use strict';
(function() {
class MainController {
constructor($http, $scope, socket, uiCalendarConfig) {
this.$http = $http;
this.socket = socket;
this.awesomeThings = [];
this.awesomeTesting = [];
this.events = [];
this.events.splice(0, this.events.length);
this.eventSources = [this.events];
console.log(this.eventSources);
/* config object */
$scope.uiConfig = {
calendar:{
height: 450,
editable: true,
header:{
left: 'month',
center: 'title',
right: 'today prev,next'
},
dayClick: $scope.alertEventOnClick,
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize
}
};
$scope.$on('$destroy', function() {
socket.unsyncUpdates('thing');
})
}
$onInit() {
this.$http.get('/api/things').then(response => {
this.awesomeThings = response.data;
this.socket.syncUpdates('thing', this.awesomeThings);
});
this.$http.get('/api/calendars').then(response => {
this.awesomeTesting = response.data;
this.awesomeTesting.forEach(function (objectItem) {
console.log('displays property in each object: ', objectItem.title);
this.events.push({
title: objectItem.title,
start: objectItem.start
});
});
this.socket.syncUpdates('calendar', this.awesomeTesting);
});
}
addThing() {
if (this.newThing) {
this.$http.post('/api/things', { name: this.newThing });
this.newThing = '';
}
}
deleteThing(thing) {
this.$http.delete('/api/things/' + thing._id);
}
}
angular.module('myApp')
.component('main', {
templateUrl: 'app/main/main.html',
controller: MainController
});
})();
答案 0 :(得分:1)
我通过使用for循环而不是.forEach()修复了这个问题,但我仍然想知道如何使用.forEach()完成答案?
for循环的解决方案:
for (var i = 0; i < this.awesomeTesting.length; i++) {
this.events.push({
title: this.awesomeTesting[i].title,
start: this.awesomeTesting[i].start
});
}
答案 1 :(得分:0)
尝试删除this.events.splice(0, this.events.length);
希望这有帮助。
答案 2 :(得分:0)
试试这个:
var that = this; 而不是取代this.events - &gt; that.events
`$onInit() {
*var that = this;*
this.$http.get('/api/things').then(response => {
this.awesomeThings = response.data;
this.socket.syncUpdates('thing', this.awesomeThings);
});
this.$http.get('/api/calendars').then(response => {
this.awesomeTesting = response.data;
this.awesomeTesting.forEach(function (objectItem) {
console.log('displays property in each object: ', objectItem.title);
*that.events.*push({
title: objectItem.title,
start: objectItem.start
});
});
this.socket.syncUpdates('calendar', this.awesomeTesting);
});
}`