Reputation: 195
Currently I have a small API where I am retrieving some user data from as I am learning angular2.
I created a user class [user.ts
]:
export class User {
first_name: string;
last_name: string;
email: string;
}
Then the service [user.service.ts
]:
import {Http} from '@angular/http';
import {User} from '../models/user';
import 'rxjs/add/operator/toPromise';
export class UserService {
private usersUrl = 'http://localhost:8000/api/user';
constructor(private http: Http) {
}
getUsers(): Promise<User[]> {
return this.http.get(this.usersUrl)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
}
private handleError(error: any) {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
I have a home component where I am trying to display the list of users for testing purposes (user list to be changed to a component later).
import {OnInit, Component} from '@angular/core';
import {UserService} from '../services/user.service'
import {User} from "../models/user";
@Component({
selector: '<home>',
templateUrl: 'app/templates/user.component.html',
})
export class HomeComponent implements OnInit {
users: User[];
constructor(private userService: UserService) {
}
getUsers() {
this.userService.getUsers().then(users => this.users = users);
}
ngOnInit() {
this.getUsers();
}
}
I provide the service in my app.component.ts:
providers: [
UserService
]
and finally I try to display the data:
<div *ngIf="users" class="ui celled animated list">
<div *ngFor="let user of users" class="item">
<div class="content">
<div class="header">{{ user.first_name }} {{ user.last_name }}</div>
{{ user.email }}
</div>
</div>
</div>
Is there anything else that needs to be done?
The JSON being retrieved is as follows:
[
{
"id":1,
"first_name":"Jameson",
"last_name":"Ziemann",
"email":"[email protected]",
"created_at":"2016-07-07 06:24:25",
"updated_at":"2016-07-07 06:24:25"
}
]
Upvotes: 3
Views: 1650
Reputation: 23506
Yes, first of all you need to add the HTTP_PROVIDERS
to the providers array:
providers: [
HTTP_PROVIDERS,
UserService
]
And second, you need to make your service injectable, so Angular 2 knows, that it actually has to resolve the constructor arguments via dependency injection:
import {Http} from '@angular/http';
import {User} from '../models/user';
import 'rxjs/add/operator/toPromise';
@Injectable() // <-- annotation for Angular 2
export class UserService {
private usersUrl = 'http://localhost:8000/api/user';
constructor(private http: Http) {
}
Also in your UserService
you try to access a data
property after deserializing it, where you already get the array. Consider removing it like so:
getUsers(): Promise<User[]> {
return this.http.get(this.usersUrl)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
Upvotes: 3