我有一个名为UserRoles的类,定义如下:

export class UserRoles
{
    public static readonly MODERATOR  = "moderator";
    public static readonly SPONSOR    = "sponsor";
    public static readonly BASE_USER  = "user";
}

我有一个名为MenuComponent的组件,在.ts文件中,我import { UserRoles } from "../../../models/userRoles";,在该组件的.html文件中,我有:
<nav class="navbar navbar-inverse">
    <div class="container-fluid">
        <ul *ngIf="currentUser.role == UserRoles.BASE_USER" class="nav navbar-nav">
            <!-- NOTE: whatever routerLinks you create here need to be added and handled properly in routing.ts -->
            <li><button class="menuButton" routerLink="leaderboard">Leaderboard</button></li>
            <li><button class="menuButton" routerLink="feed">Feed</button></li>
            <li><button class="menuButton" routerLink="score">Score</button></li>
            <li><button class="menuButton" routerLink="my-posts">My Posts</button></li>
            <li><button class="menuButton" routerLink="create-posts">Create Posts</button></li>
            <li><button class="menuButton" routerLink="edit-posts">Edit Posts</button></li>
        </ul>
        <ul *ngIf="currentUser.role == UserRoles.MODERATOR" class="nav navbar-nav">
            <!-- NOTE: whatever routerLinks you create here need to be added and handled properly in routing.ts -->
            <li><button class="menuButton" routerLink="flagged-users">Flagged Users</button></li>
            <li><button class="menuButton" routerLink="flagged-posts">Flagged Posts</button></li>
            <li><button class="menuButton" routerLink="flagged-comments">Flagged Comments</button></li>
            <li><button class="menuButton" routerLink="my-messages">My Messages</button></li>
            <li><button class="menuButton" routerLink="create-messages">Create Messages</button></li>
        </ul>
        <ul *ngIf="currentUser.role == UserRoles.SPONSOR" class="nav navbar-nav">
            <!-- NOTE: whatever routerLinks you create here need to be added and handled properly in routing.ts -->
            <li><button class="menuButton" routerLink="balance">Balance</button></li>
            <li><button class="menuButton" routerLink="popular-users">Popular Users</button></li>
            <li><button class="menuButton" routerLink="my-advertisements">My Advertisements</button></li>
            <li><button class="menuButton" routerLink="create-advertisements">Create Advertisements</button></li>
        </ul>
    </div>
</nav>

当我启动ng serve并测试它时,上面的任何一个都不会呈现,当我检查开发人员控制台时,我会收到一条基本上告诉我UserRoles未定义的消息。
有什么我应该做的,无论是在这里还是在课堂上?

最佳答案

模板中的表达式希望使用组件类的变量和方法。为了访问模板中UserRoles的值,可以将该类分配给组件类的成员变量:

import { Component } from '@angular/core';
import { UserRoles } from "./user-roles.model";

@Component(
    ...
)
export class UserComponent {
    public UserRolesClass = UserRoles;
    ....
}

并在模板中使用该变量:
<ul *ngIf="currentUser.role == UserRolesClass.BASE_USER" class="nav navbar-nav">

该技术如this stackblitz所示。

07-27 13:22