You are missing couple of relevant sections in DI.
There are multiple ways to inject using provide and @inject or using @Injectable decorators. Here you, for instance, decorate your service with @Injectable i.e
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
// You do not need to do this, but creating an interface for more strong typing. You could as well create a User class here and use that as view model.
interface IUser{
name:string;
}
@Injectable()
class UserServices {
users: Array<IUser>;
constructor(private http:Http) {}
getUsersList():Observable<Array<IUser>> {
return this.http.get('./users.json')
.map((res: Response) => res.json());
}
}
export {IUser, UserServices};
Inject UserServices and HTTP_PROVIDERS at the root, Generally you inject the services that you need as singleton across your app at the app root level. If not, you can inject the service alone in the UserComponent decorator's providers array.
i.e
bootstrap(UsersComponent, [HTTP_PROVIDERS, UserServices])
or within the component's decorator:
@Component({
selector: 'users',
template: `<h1>Users</h1>
<div *ngFor="#user of users">
{{user.name}}
</div>
`,
providers:[UserServices]
})
Consume this in your component and subscribe 1 to the returned observable.
export class UsersComponent {
users: Array<IUser>;
constructor(userServices: UserServices) {
userServices.getUsersList().subscribe(users => this.users = users);
}
}
1You can also use async pipe (application of this depends upon the use case) and set the value of this.users as the observable instead of subscribing them explicitly.
<div *ngFor="#user of users | async">
{{user.name}}
</div>
and
this.users = userServices.getUsersList();
Note: In the example i just imported map operator in order to get the map as a part of observable returned by http (import rxjs/add/operator/map) since this is not mapped in the system Js config paths property at a global level.
Here is a working plunker Demo.