簡體   English   中英

如何在角度使用服務

[英]how to use a service in angular

學習了angularJS之后,我便開始學習angular2.2 +。

還有一個我無法解決的小問題。

我將向html視圖顯示一個集合。

獲得服務:

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;
    }

}

和這樣的組件:

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']);
            }
        }

    }

}

並嘗試在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>

但是我無法運行它。 如何使用組件中的方法“ getUserCollection”,如何在html視圖中直接使用服務?

關於n00n

創建一個將用戶保存在組件內部的數組,如下所示:

users: object[];

從服務輸入ngOnInit分配值

ngOnInit() {
    this.users = this._userService.getUsers();
}

模板應該是

 <mat-option *ngFor="let user of users" [value]="user.id">
       {{ user.name }}
 </mat-option>

我將創建一個名為

userList = [];

然后在ngInit上,我會將數據從服務加載到您的列表中

ngOnInit() {
    this.userList = this._userService.getUsers();
}

從這一刻起,您只需要在模板中調用它

*ngFor="let user of userList”

另一種選擇是將您的構造函數更改為

constructor(public _userService: UserService) {}

然后在您的模板中,您可以像這樣訪問users

<mat-option *ngFor="let user of _userService.users" [value]="user.id">

如果您的服務與其他組件共享並且用戶對象是動態的,則此方法特別有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM