0

here is the source code:

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 );
    }  
  }

`

it works fine,but if I add curly braces for "respone.json", then visual stdio code hint a error(see below). after add the curly braces the source code like below:

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 );
    }  
  }

the error is on word "this.posts" of the last line,the erroris :[ts] Type 'void' is not assignable to type 'any[]'.

why?

pies
  • 61
  • 1
  • 1
  • 5

1 Answers1

4

.map((respone) => respone.json()) is actually the same as this:

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

While .map((respone) => { respone.json() }) is similar to this:

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

Therefore, in your second code block, the respone.json() is just dismissed.

fstanis
  • 5,234
  • 1
  • 23
  • 42