在 MEAN Stack 中将用户 ID 传递到前端

2025年3月17日 | 阅读 3 分钟

在上一节中,我们成功添加了服务器端授权。在本节中,我们将把用户 ID 传递到前端。现在,每个用户都可以点击删除按钮,即使是经过身份验证但没有创建帖子的用户。我们将调整我们的前端代码。

我们将进入 post-list 组件,在那里我们向任何经过身份验证的用户显示编辑和删除按钮。但这现在不再正确了。我们想更严格地限制它。我们只想向那些经过身份验证并且是帖子创建者的用户显示这些按钮。现在,这意味着我们需要先将用户 ID 获取到前端。

1) 我们将回到我们的 js 文件,在那里我们创建登录路由。我们将到达我们返回 token 和 expiresIn 的地方。现在,我们不只是想返回 token 和 expiry。我们还想以以下方式返回用户 ID


Passing the User Id to the Frontend in MEAN Stack

2) 将用户 ID 传递到前端后,我们需要将该信息也存储在前端。我们将回到我们的 service.ts 文件,在那里我们发送该登录请求。在那里,我们将创建一个新的属性,即 userId,它将是字符串类型。在 login 函数中,当我们在返回响应时,我们将该值设置为 userId 属性。为此,我们需要更新我们的 typescript 代码,因为现在我们也有了 userId 字段以及 token 和 expiresIn。


Passing the User Id to the Frontend in MEAN Stack

3) 现在,我们可以在我们的应用程序中使用这个 userId 了。为此,我们将添加一个新方法,即 getUserId()。在这个方法中,我们将简单地返回 userId,就像


Passing the User Id to the Frontend in MEAN Stack

4) 现在,我们将从我们的 post-list 组件中获取该用户 ID,因为我们需要将其与我们正在查看的帖子的 ID 进行比较。所以,我们将回到我们的 post-list.component.ts 文件,在那里我们将添加一个新的属性,即 userId,最初它将是未定义的。之后,我们将在 ngOnInit() 方法中获取 userId 并将其分配给 userId 属性。


Passing the User Id to the Frontend in MEAN Stack

5) 如果身份验证发生变化,我们还想获取更新后的用户 ID。所以,这意味着我们也在侦听器中设置 userId 以监听我们的 AuthStatusChange。


Passing the User Id to the Frontend in MEAN Stack

6) 如果用户从经过身份验证切换到未经身份验证,我们想从 getUserId() 方法中的侦听器中获取 null 或 undefined。因此,每当我们注销时,我们都必须在 auth 服务中重置 userId 字段。因此,我们将在 logout() 方法中将 userId 设置为 null。


Passing the User Id to the Frontend in MEAN Stack

7) 此外,我们还获得了 autoAuthUser() 方法,我们根据存储在本地存储中的数据来登录用户。我们尚未将 userId 存储在本地存储中,但我们需要这样做,因为我们将来也需要该信息。因此,在 saveAuthData() 方法中,我们希望获得一个额外的字段,即 userId,它是一个字符串类型。我们像这样存储它


Passing the User Id to the Frontend in MEAN Stack

8) 我们还需要在 clearAuthData() 方法中删除该数据。


Passing the User Id to the Frontend in MEAN Stack

9) 在 getAuthData() 方法中,我们也需要获取它。我们将通过以下方式获取它


Passing the User Id to the Frontend in MEAN Stack

10) 现在,在 autoAuthUser() 方法中,我们还使用我们的 auth Information.userId 初始化 userId,就像


Passing the User Id to the Frontend in MEAN Stack

11) 我们要做的最后一件事是,我们期望 userId 作为 saveAuthData() 上的参数。因此,我们将 userId 从我们调用它的函数传递给该函数。


Passing the User Id to the Frontend in MEAN Stack

现在,userId 已被正确管理,在下一节中,我们将把它与附加到帖子的 creator Id 一起使用。