0

I am trying to be pull data from API using Angular2, and bind it to view. After request been done, my component only gets array object [object Object],[object Object],[object Object]. Can I get any help on extracting the object so that "*ngFor" can read each object. I want to be able to bind data to view.

**This is my API**
[{
    _id: "578c8c670f3cd0941efb337c",
    name: "John",
    gender: "Male",
    age: "34",
    __v: 0,
},
{
    _id: "5794a90f96391dcc2436e43f",
    name: "Valur",
    gender: "Male",
    age: "22",
    __v: 0,
},
{
    _id: "5794abad70df28541eab170b",
    name: "Paul",
    gender: "Male",
    age: "43",
    __v: 0,
}]

UserService is like:

import { Http } from 'angular2/http';
constructor(private _http: Http) { }

getuser(): Observable<any> {
     return this._http.get('http://localhost:1000/api/users')
     .map(res => res.json());
}

This my angular with service that handle request.

import { UserService } from '../services/userservice';

constructor(private userService: UserService) { }
_data: Object;

getUser():void {
    this.userService.getuser()
      .subscribe(data => this._data = data,
      error => console.log(error));

    console.log(this._data); //this part doesn't pull data at all.
}


//My view
<div *ngFor="#u of _data">
   {{u.name}} //this part gives me an error
</div>

 //But when i try to pull data from "subscribe" like this:
<div>
   {{_data | json }} //data is available
</div>
2
  • What does the output of {{_data | json}} look like? Commented Jul 25, 2016 at 8:05
  • 3
    It seems you're using quite an old Angular2 version. In recent Angular2 versions the syntax is <div *ngFor="let u of _data"> Commented Jul 25, 2016 at 8:06

2 Answers 2

1

Try this.

import { UserService } from '../services/userservice';

_data: any[];
constructor(private userService: UserService) { this._data = [];}

getUser():void {
  this.userService.getuser()
    .subscribe(data => {this._data = data; console.log(this._data);}
                error => console.log(error));
 }


 //My view
 <div *ngFor="#u of _data">
   {{u?.name}} //this part gives me an error
 </div>
Sign up to request clarification or add additional context in comments.

Comments

0

I agree with Günter, the error is exactly in the syntax of the *ngFor, i have tested your code, and i made a working example:

https://github.com/TheSwash/ng2-http-service

But quickly the correct syntax should be:

<div *ngFor="let user of users">
   {{user.name}}
</div>

Besides i highly recommend you to update your angular version, you're using the beta. Currently you can use Angular-CLI: https://cli.angular.io/

The example above is made with Angular-CLI.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.