我正在尝试从Angular 2中的UserService获取静态数据。文档中的所有内容都看起来不错,但由于某些原因它无法正常工作。
这是我的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();
}
}
这是我的UsersService.ts
import { Injectable } from '@angular/core';
@Injectable()
export class UsersService {
users =['krishna','ravi','ram','ramesh','sita'];
getUsers() {
return this.users ;
}
}
正如预期的那样,它的输出应该是
<h3>Users </h3>
<ul>
<li>Krishna</li>
<li>Ravi</li>
<li>Hari</li>
<li>etc</li>
</ul>
但它不会重复* ngFor循环。我也打印了{{users}},它返回空。请告诉我这里有什么问题。
答案 0 :(得分:4)
constructor
export class UsersComponent {
users;
title;
constructor( private usersService: UsersService) {
}
ngOnInit() {
this.users = this.usersService.getUsers();
}
}