[英]how to use a service in angular
after I learned angularJS I start learning angular2.2+. 学习了angularJS之后,我便开始学习angular2.2 +。
And got a small problem I cannot solve. 还有一个我无法解决的小问题。
I will display a collection to the html view. 我将向html视图显示一个集合。
Got a service: 获得服务:
import {Injectable} from '@angular/core';
@Injectable()
export class UserService {
users: object[];
constructor() {
this.users = [
{
id: 1,
name: 'first user'
},
{
id: 2,
name: 'second user'
}
];
}
getUsers() {
return this.users;
}
}
and the component like this: 和这样的组件:
import {Component, OnInit} from '@angular/core';
import {UserService} from './user.service';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
providers: [UserService]
})
export class UserComponent implements OnInit {
constructor(private _userService: UserService) {
}
ngOnInit() {
}
getUserCollection() {
return this._userService.getUsers();
}
onChange(event) {
// nun brauche ich einen service dem ich den aktuellen wert zuweisen kann der mir eine liste der user geben kann usw.
for (const item of this._userService.getUsers()) {
if (event.source.value === item['id']) {
console.log(item['id']);
}
}
}
}
and tried to use it in the html view 并尝试在html视图中使用它
<mat-form-field>
<mat-select placeholder="Select User" (change)="onChange($event)">
<mat-option *ngFor="let user of getUserCollection()" [value]="user.id">
{{ user.name }}
</mat-option>
</mat-select>
</mat-form-field>
But I cannot get it running. 但是我无法运行它。 How can I use the method 'getUserCollection' from component and how could i directly use the service in the html view? 如何使用组件中的方法“ getUserCollection”,如何在html视图中直接使用服务?
regards n00n 关于n00n
Create an array which holds your users inside your component as follows, 创建一个将用户保存在组件内部的数组,如下所示:
users: object[];
assign the values from service insige ngOnInit 从服务输入ngOnInit分配值
ngOnInit() {
this.users = this._userService.getUsers();
}
and the template should be, 模板应该是
<mat-option *ngFor="let user of users" [value]="user.id">
{{ user.name }}
</mat-option>
I would create a public property called 我将创建一个名为
userList = [];
Then on ngInit I would load the data from the service to your list 然后在ngInit上,我会将数据从服务加载到您的列表中
ngOnInit() {
this.userList = this._userService.getUsers();
}
From this moment you just need to call it in the template 从这一刻起,您只需要在模板中调用它
*ngFor="let user of userList”
Another alternative is to change your constructor to 另一种选择是将您的构造函数更改为
constructor(public _userService: UserService) {}
then in your template you can access users
like this: 然后在您的模板中,您可以像这样访问users
:
<mat-option *ngFor="let user of _userService.users" [value]="user.id">
This approach can especially be useful if your service is shared with other components, and your users object is dynamic. 如果您的服务与其他组件共享并且用户对象是动态的,则此方法特别有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.