1

I'm new at angular2 and I'm trying to get data from web api with my angular2 application. I'm using Visual Studio 2015. I have no error but the datas just don't display, I should get all the users Login display on my html page but it's empty, it shows the right number of existing Logins though, here's the result :

enter image description here

my component :

import { Component } from "@angular/core";
import { Http, Response } from "@angular/http";

@Component({
    selector: "team",
    templateUrl: "../Scripts/components/team/team.component.html"
})
export class TeamComponent {
    public users: IUserID[];
    private _userIdUrl = "http://localhost:61142/api/UserID";
    constructor(private http: Http) {
        http.get(this._userIdUrl).subscribe(result => {
            this.users = result.json();
        });
    }
}

interface IUserID {
    Login: string;
}

and my controller :

 [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class UserIDController : ApiController
    {
        IUserIDBusiness userIDBusiness;

        public UserIDController()
        {
            userIDBusiness = WebApiConfig.userIDBusiness;
        }

        public IEnumerable<UserID> Get()
        {
            return userIDBusiness.GetAll();
        }

[EDIT] Html :

<ul>
    <li *ngFor="let user of users">
        {{ user.Login }}
    </li>
</ul>

What am I missing ?

2
  • Can you post your HTML component too Commented Mar 23, 2017 at 9:03
  • To partly answer your question.... You are missing the template and JSON structure from your question ;) Commented Mar 23, 2017 at 9:03

2 Answers 2

2

Change {{ users.Login }} to {{ user.Login }}

Sign up to request clarification or add additional context in comments.

4 Comments

Assuming that the 'Login' property is valid/existing on the IUserID type.
I made the change but doesn't make a difference :/
console.log(this.users) inside subscription and check if you get an array of objects with Login property.
ok, it does't display anything in the console, even if I write something in the console.log
1

A better approach for this is to actually create a service where you make the http call, instead of making the call in the constructor.

Start by creating a service which could look like this for example:

import { Injectable } from "@angular/core";
import { Http, Response } from '@angular/http';
import 'rxjs/operator/map';

@Injectable()
export class UserService extends ServiceBase {
    private _userIdUrl = "http://localhost:61142/api/";

     getUserData(userId: number) {
     return http.get(`this._userIdUrl/${userId}`)
        .map((response: Response) => response.json());
     }
}

After creating your service you should inject it in your component(having said that you registered the service in the app.module providers)

Read more about services if you don't know how to register your service.

Then your component would look something like this:

import { Component } from "@angular/core";
import { UserService } from '..' // import the service where you stored it.

@Component({
    selector: "team",
    templateUrl: "../Scripts/components/team/team.component.html"
})
export class TeamComponent implements OnInit {
    public users: IUserID[];
    constructor(private _userService: UserService) {
    }
}

ngOnInit() {
    this._getUserData();
}

private _getUserData() {
    this._userService.getUserData(userId) // pass the userId here. you can get it from the router params or somewhere else.
        .subscribe(response => {
            if(response){
                this.users = <IUserID>response.json();
            }
        },
        error => console.log(error)) // handle errors the way you like.
}

interface IUserID {
    Login: string;
}

You see, by taking this approach you abstract the way data is fetched from the server and your component has no idea or does not care about how data is fetched, which is good because this means you decompled your logic for getting data from the component.(Not to mention your code in the component gets a lot cleaner)

5 Comments

Thx for you answer, I'm gonna try this !
@SamCaneau, sure thing. Let me know if you have any issues. And make sure you are getting the right data from the server.
I got an error on map : Map does not exist on type Observable<Response> .. I made the import though
I tried all the possible ways of import for map with rxjs, I still get that error :/
@SamCaneau, I've edited my answer. Check it out. Plus I've changed the code so now your service accepts an userId parameter and makes the http call according to that Id.

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.