Leff
Leff

Reputation: 1360

Angular 4 - getting json data from service not working

I have a file with dummy json data in my project, where I would like to get that data from and make a list with in my template with that. I have set up a method in services where I get the data from that json file.

get(): Observable<string[]> {
    return this.http.get('services/getUsers.json')
                    .map((res: Response) => console.log(res.json()))
                    .catch(this.handleError);
 }

That part works fine, I get that data from the console.log(res.json() in the method. The component that I have set up looks like this:

users: any[] = [];

ngOnInit() {
    this.getAddresses();
}


getUsers() {
   this.usersService.get()
      .subscribe(
        users => this.users = users,
        error => this.errorMessage = <any>error
    );
}

But, when I try to display that data in the template, I don't get anything:

<div class="row">
    <div class="col-md-6">
      <ul class="list-group posts">
          <li *ngFor="let user of users" class="list-group-item">
              {{ user.name }}
          </li>
      </ul>
    </div>
</div>

Upvotes: 1

Views: 857

Answers (1)

eko
eko

Reputation: 40677

Change

.map((res: Response) => console.log(res.json()))

to

.map((res: Response) => res.json())

which is the short version of

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

you need to return something in your map function

Upvotes: 2

Related Questions