在 MEAN Stack 的前端使用用户 ID

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

在我们之前的章节中,我们成功地将用户 ID 传递到了前端。现在我们正在处理用户 ID,在本节中,我们将在 post-list 组件中使用用户 ID 和创建者。我们将按照以下步骤在前端使用它

1) 我们已经在 post-list 组件的 typescript 文件中设置了 userId 属性。 我们将把它与我们在每个帖子上的创建者信息结合使用。 在 post-list 组件中,我们在屏幕上呈现的每个帖子都将具有创建者 ID。 我们将转到 html 文件,在那里我们将向 ngIf 语句添加另一个条件。 我们希望在用户经过身份验证且 userId 等于帖子的创建者时显示编辑和删除按钮。


Using the User Id on the Frontend in MEAN Stack

2) 由于我们的帖子模型,我们在模板中收到一个错误。 在帖子模型中,没有创建者字段。 因此,我们将在帖子模型中添加创建者字段,并且该字段也将是字符串类型。


Using the User Id on the Frontend in MEAN Stack

3) 添加此之后,我们在 post.service.ts 文件中更新帖子时会收到一个错误。 我们收到此错误是因为我们没有发送创建者 ID。 我们将简单地将创建者设置为 null。


Using the User Id on the Frontend in MEAN Stack

4) 我们当然可以获取当前登录用户的 ID,但这会为用户打开操纵的窗口,而我们不希望这样。 因此,我们需要在服务器上处理此问题。 我们将返回到 posts.js 路由,在那里我们更新帖子,我们需要再次添加创建者字段,但这次我们从请求中获取用户数据。


Using the User Id on the Frontend in MEAN Stack

5) 我们还将在 post-create 组件的 typescript 文件中收到一个错误。 在那里,当我们编辑帖子时,我们有一个帖子正在尝试加载。 在那里,我们缺少创建者字段,因此我们将添加它,如下所示


Using the User Id on the Frontend in MEAN Stack

6) 这将产生一个错误,因为我们没有在获取单个帖子的 post-service 中添加创建者字段。 因此,我们将在 post 服务的 getPost() 方法中添加它


Using the User Id on the Frontend in MEAN Stack

一切看起来都不错。 现在我们将返回到我们的 Angular 应用程序并检查我们的应用程序是否正常工作。

Using the User Id on the Frontend in MEAN Stack
Using the User Id on the Frontend in MEAN Stack
Using the User Id on the Frontend in MEAN Stack
Using the User Id on the Frontend in MEAN Stack
Using the User Id on the Frontend in MEAN Stack

我们的应用程序运行良好,这正是我们想要的。 从下一节开始,我们将开始一个新模块,即处理错误。

下载完整项目(Authorization.zip)


下一主题错误拦截器