为什么箭头功能没有传递参数? [英] Why arrow function is not passing arguments?

查看:121
本文介绍了为什么箭头功能没有传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用w/rxjs来观察界面上的用户事件.但是,在将参数传递给箭头函数中的方法时,我遇到了这个非常简单的问题.问题出在这里:

I'm using angular w/ rxjs to observe user events on the interface. However, I'm having this really simple problem with passing arguments to a method in an arrow function. Here is the problem:

这不起作用:搜索项未传递给this.searchFacilities

This is not working: searchterm is not being passed to this.searchFacilities

ngOnInit() {
 this.searchTerm$.subscribe(searchterm => this.searchFacilities);/**Not working here**/
}

searchFacilities(term: string){
  console.log(term);
  this.facilityservice.searchFacilities(term)
    .subscribe(results => this.facilityList = results);
}

但这可行:

this.searchTerm$.subscribe(searchterm => { this.searchFacilities(searchterm); })

很显然,我还有其他非常轻松的解决方案,但是我真的很想了解为什么我的第一种方法行不通.谢谢!

Clearly, I have other solutions that are pretty painless, but I really want to understand why my first approach is not working. Thanks!

推荐答案

小澄清.该文档说您需要将回调传递给subscribe(),并且该回调将接收Observable发出的值.

Small clarification. The doc says you need to pass a callback to subscribe() and that this callback will receive the value(s) emitted by the observable.

我们可以这样写:

const myCallBack = (val) => console.log(val);
Observable.range(0, 3).subscribe(myCallBack);

在您的情况下,您已经有一个回调this.searchFacilities.
这意味着您可以简单地编写:

In your case you already have a callback, this.searchFacilities.
This means you can simply write:

this.searchTerm$.subscribe(this.searchFacilities);

就像您可以将我的原始示例重写为:

Just like you can rewrite my original example to:

// Now `console.log` is the callback!
Observable.range(0, 3).subscribe(console.log);

换句话说,问题不在于为什么箭头功能未传递参数".问题在于您创建了一个箭头函数,其主体为 IS 您的回调,而不仅仅是直接使用回调.

In other words, the problem is not "Why arrow function is not passing arguments". The problem is that you created an arrow function whose body IS your callback, instead of just using your callback directly.

代码的扩展版本如下所示:

The expanded version of your code would look like this:

const myCallBack = (searchterm) => {
  return this.searchFacilities;
}

如您所见,searchFacilities既不被调用也不接收searchterm参数.

As you can see, searchFacilities is neither invoked nor does it receive the searchterm param.

通过编写以下代码,您可能会遇到使用NON-ARROW函数的相同问题(尽管arrow函数的语法确实使错误更可能发生并且更加隐蔽):

You could have run into the same problem with a NON-ARROW function by writing the following code (although the syntax of arrow functions does make the mistake more likely and insidious):

const myCallBack = function(searchterm) {
  return this.searchFacilities;
}

这篇关于为什么箭头功能没有传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆