This question already has answers here:
Curly Brackets in Arrow Functions
                                
                                    (2个答案)
                                
                        
                2年前关闭。
            
        

这是源代码:

export class PostComponent implements OnInit {

    posts: any[];

    constructor(private http: Http, private service: PostService) {
    }
    getAll1() {
    const url = 'http://jsonplaceholder.typicode.com/posts';
    this.http.get(url)
    .map((respone) => respone.json())
    .subscribe(posts => this.posts = posts );
    }
  }


`

它工作正常,但是如果我为“ respone.json”添加大括号,则可视stdio代码会提示错误(请参见下文)。
添加花括号后的源代码如下:

export class PostComponent implements OnInit {

    posts: any[];

    constructor(private http: Http, private service: PostService) {
    }
    getAll1() {
    const url = 'http://jsonplaceholder.typicode.com/posts';
    this.http.get(url)
    .map((respone) => {respone.json();})
    .subscribe(posts => this.posts = posts );
    }
  }


错误出现在最后一行的单词“ this.posts”上,错误是:[ts]类型“ void”不能分配给类型“ any []”。

为什么?

最佳答案

.map((respone) => respone.json())实际上与此相同:

.map((respone) => { return respone.json() })


虽然.map((respone) => { respone.json() })与此类似:

.map((respone) => { respone.json(); return undefined; })


因此,在您的第二个代码块中,respone.json()只是被关闭了。

08-19 07:46