2017-02-18 15 views
2
import { Component, Input, Output, OnInit, OnChanges } from '@angular/core'; 
import { ViewComponent } from '../view/view.component'; 
import { HitoService } from '../../services/hito.service'; 

@Component({ 
    selector: 'app-time-line', 
    templateUrl: './time-line.component.html', 
    styleUrls: ['./time-line.component.css'], 
    providers: [HitoService] 
}) 

export class TimeLineComponent implements OnChanges, OnInit { 
    @Input() calbuscador: String; 
    @Input() idcalbuscador: String; 
    public pepe: String 
    nom_cal1: any; 
    hito1: any = {}; 
    hito2: any = {}; 

    constructor(public _hitoService: HitoService) { 
    } 

    ngOnInit() { 
    } 
    ///we retrieve the value sento to this component in OnChanges 
    ngOnChanges() { 

this.nom_cal1 = this.calbuscador; 
this.drawtimeline(this.nom_cal1, this._hitoService, this.idcalbuscador); 
    } 

    result: any[] = []; 
    drawtimeline(nom_cal, _hitoService, idcalbuscador) { 

    var container = document.getElementById('timeLine'); 
    //alert("id cal sele es :" + idcalbuscador); 

    var k = 0; 
    var j = 0; 

    var master = new vis.DataSet(); 
    var items = new vis.DataSet(); 

     this.result.push({ "_id": this.idcalbuscador, 
     "title": nom_cal }); 


    this.result.forEach(function (ev) { 
     master.add([{ id: ev._id, content: ev.title, cal_id: ev._id }]); 
     var g = ev._id; 

     for (var i= 0; i<this.result.length; i++){ 
    console.log("hola"); 
    console.log(this.result[i]._id); 
this._hitoService.getHitos(this.result[i]._id) 
       .subscribe(hito2 => { 
       this.hito2 = hito2 
      var items: any; 
      items = hito2; 

      items.forEach(function (item) { 
      items.add([{ id: k, group: g, start: item.start_datetime, end: item.end_datetime, style: itemStyle(item.design), className: "pepe" }]); 
      k++; 
      }); 
      j++; 
     }); 

     } 
    }); 

我试图使用vis.js实施时间表,我检索名称和时间表的ID想在这个类组件,然后在ngOnChanges我调用该函数画出时间表传递给它的时间线的名称,它的ID和其他的服务来获得这个特定的时间线的观测项目。我将存储时间表(结果)我要查看,然后可观察到的我订阅,添加时间表的项目的数组。第一次的foreach()将结果数组中删除第一个元素,得到物品,此结果和第二的foreach(的观测)将通过观测项目和打印的项目,然后重新开始,并移动到下一个。但我在浏览器控制台中得到的是:TypeError:这是未定义的。也许不是使在forach()可以使用服务的foreach()内

+0

您需要创建一个箭头函数'()=> {}'来绑定'this'。 – jonrsharpe

回答

1

分配电流this另一个变量(比如,that)然后,用that到您的回调。

注:内回调函数this改为由该函数被调用JavaScript的上下文。

const that = this;  // save the current 'this' to 'that' variable 

this.result.forEach(function (ev) { 
     master.add([{ id: ev._id, content: ev.title, cal_id: ev._id }]); 
     var g = ev._id; 

     for (var i= 0; i< that.result.length; i++){ 
     console.log("hola"); 
     console.log(that.result[i]._id); 
     that._hitoService.getHitos(that.result[i]._id) 
       .subscribe(hito2 => { 
       that.hito2 = hito2 
       var items: any; 
       items = hito2; 

       .... 
      .... 
      .... 
2

您可以使用您的forEach内的箭头功能使用封闭的范围,以保持使用该服务。

this.result.forEach((ev) => { 
 
    // your code here 
 
}

相关问题