在Angular 8中,你可以通过以下步骤从JSON REST API创建枚举:
export interface User {
id: number;
name: string;
role: string; // 这里假设API响应中的角色是一个字符串
}
export enum UserRole {
Admin = 'admin',
Moderator = 'moderator',
User = 'user'
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from './user';
@Injectable({
providedIn: 'root'
})
export class UserService {
private apiUrl = 'https://api.example.com/users';
constructor(private http: HttpClient) { }
getUsers(): Observable {
return this.http.get(this.apiUrl);
}
}
import { Component, OnInit } from '@angular/core';
import { UserService } from './userService';
import { User } from './user';
import { UserRole } from './enum';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
users: User[];
constructor(private userService: UserService) { }
ngOnInit() {
this.userService.getUsers().subscribe(users => {
this.users = users;
});
}
getUserRole(role: string): string {
return UserRole[role];
}
}
-
{{ user.name }} - {{ getUserRole(user.role) }}
现在,当你运行应用程序时,它将从API获取用户数据,并将用户角色作为枚举类型显示在用户列表中。