问题描述
我在代码中遇到了一个小问题,这让我很困惑,并希望有人能解释为什么会这样做。
I came across a little problem in my code which was kind of confusing to me and hope someone could explain why it does the things it does.
代码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 中取出括号并将任务放在一行上。
The key difference between these two code is that in Code 2 I placed the brackets after the arrow function to add my tasks inside those brackets and in Code 1 I took the brackets out and place the task on one line.
我的问题是为什么来自服务器端的对象在 Code2 中以未定义的方式返回,其中的angular2方法是angular2提供的,而 Code1 返回我怀疑的对象。
My question is why does my object coming from the server side coming back as undefined in Code2 with the subscribe method that angular2 provided while Code1 returns the object I suspect.
推荐答案
(response:Response) => response.json()
这是简写:
(response:Response) => { return response.json(); }
{}
让你添加语句。没有它们,该函数只运行一个语句并返回其值。
The {}
let you add multiple statements inside the block. Without them, the function just runs the one statement and returns its value.
文档:
这篇关于带括号的ES6箭头功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!