2017-10-06 42 views
-1

我正在使用Angular 4应用程序中的d3.js。我正试图调用一个函数,但它会引发一个错误,如ERROR TypeError: this.highlightNodes is not a functionthis.someFunction(params)不是Angular 4中的函数

下面的代码,我工作:

import {Component, OnInit} from '@angular/core'; 

declare let d3:any; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.scss'] 
}) 
export class AppComponent implements OnInit { 

    ngOnInit() { 
    this.networkGraph(); 
    } 

    networkGraph() { 
    d3.netJsonGraph("../assets/json/network.json", 
     { 
     el: "#randomDiv", 
     onClickNode: function (url, opts) { 
      //Here's the error being thrown 
      this.highlightNodes(url, "nodes", true); 
     } 
     } 
    ); 
    } 

    highlightNodes(url, type, initial) { 
    console.log("Its working"); 
    } 
} 

使用bind(this)是没有帮助,因为它是局部结合。请帮我解决这个问题,如何以正确的方式调用函数。

+0

要调用一个单击处理这不是一个箭头函数中的方法。这将改变上下文。尝试'nClickNode:(url,opts)=> {}' – Rajesh

+1

必须有'这个'的双关语(双关语意思:) :) – abhishekkannojia

回答

2

这是指onClickNode在这种情况下,使用箭头功能:

onClickNode: (url, opts) => { 
    //Here's the error being thrown 
    this.highlightNodes(url, "nodes", true); 
} 
+2

你有没有发布电话答案? – Rajesh

+0

@Rajesh哈哈!你怎么知道的?无论如何更新它 – Sajeetharan

+0

你的代表用户必须知道技巧和重要性来格式化答案。所以如果格式化关闭,这意味着你正在使用手机,并很难在那里格式化。 – Rajesh

1

使用箭头功能保存上下文

onClickNode: (url, opts) => { 
    this.highlightNodes(url, "nodes", true); 
} 
1

当您使用function关键字,它隐藏范围this。改用箭头功能。

替换此行:

onClickNode: function (url, opts) { 

...这一点:

onClickNode: (url, opts) => {