I am trying to get static data from UserService in Angular 2. Everything looks ok from the documentation but it is not working for some reason.
Here is my UserComponent.ts
import {Component ,OnInit } from '@angular/core';
import {UsersService} from './users.service';
@Component({
selector: 'users',
template: `<h3>Users </h3>
<ul>
<li *ngFor="let user of users">{{user}}</li>
</ul>
`,
providers:[UsersService]
})
export class UsersComponent {
users;
title;
construct( usersService: UsersService){
this.users=usersService.getUsers();
// i also tried this but no luck. this.users = this.usersService.getUsers();
}
}
And here is my UsersService.ts
import { Injectable } from '@angular/core';
@Injectable()
export class UsersService {
users =['krishna','ravi','ram','ramesh','sita'];
getUsers() {
return this.users ;
}
}
As expected its output should be
<h3>Users </h3>
<ul>
<li>Krishna</li>
<li>Ravi</li>
<li>Hari</li>
<li>etc</li>
</ul>
But it is not repeating on *ngFor loop. I printed {{users}} as well and it returns empty. Please suggest me what is the issue here.
There is spelling mistake for constructor
export class UsersComponent {
users;
title;
constructor( private usersService: UsersService) {
}
ngOnInit() {
this.users = this.usersService.getUsers();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.