带括号的ES6箭头功能

时间:2016-08-02 21:27:09

标签: javascript angular ecmascript-6

我在代码中遇到了一个小问题,这让我感到困惑,希望有人能解释为什么会这样做。

代码1

sendText(){
    return this.http.get('/api')
        .map((response:Response) => response.json());
}

代码2

sendText(){
    return this.http.get('/api').map((response:Response) => {
        response.json();
    });
}

这两个代码之间的主要区别在于,在代码2 中,我在箭头功能之后放置括号,将我的任务添加到这些括号中,并在代码1 中括号出来并将任务放在一行上。

我的问题是为什么来自服务器端的对象在 Code2 中以未定义的方式返回,其中angular2提供了subscribe方法,而 Code1 返回了我怀疑的对象。

1 个答案:

答案 0 :(得分:12)

(response:Response) => response.json()

这是的简写

(response:Response) => { return response.json(); }

{}允许您在块中添加多个语句。没有它们,该函数只运行一个语句并返回其值。

文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

相关问题