繁体   English   中英

从 Spring Boot 转发到特定的 Angular 组件

[英]Forward from Spring Boot to a specific Angular component

在我的 Web 应用程序中,Angular UI 用作 Spring Boot 应用程序的静态资源(通过将构建的 Angular 应用程序复制到 Spring Boot 应用程序的/resources/static文件夹中)。

我所有的 Spring 端点都以/api为前缀。

来自 Angular 应用的相关路线:

{ path: 'login', component: LoginComponent },
{ path: 'registration', component: RegistrationComponent },
{ path: '', pathMatch: 'full', redirectTo: 'login' }

这很好用,当我启动 Spring Boot 应用程序并在浏览器中导航到http://localhost:8080时,就会显示 Angular 应用程序的登录页面。

有问题的部分:

通过将http://localhost:8080/loginhttp://localhost:8080/registration粘贴到浏览器中并按 Enter 直接导航到登录或注册页面将不起作用,因为该请求将命中 Spring Boot 应用程序和由于它没有匹配的映射,它将返回 404。

我做的第一件事显然是在 Stackoverflow 上搜索解决方案,大多数答案都建议使用匹配的映射将请求转发到根目录,因此我添加了以下Controller

@Controller
public class ViewController {

    @RequestMapping({"/login", "/registration"})
    public String forward() {
        return "forward:/";
    }
}

这解决了 404 错误。

问题是即使我直接导航到http://localhost:8080/registration ,我LoginComponent被转发到登录页面并显示LoginComponent

我想要实现的是当我在浏览器中导航到http://localhost:8080/registration时,然后确实转到注册页面并显示 Angular 应用程序的RegistrationComponent

这甚至可能吗? 如果是这样,我真的很乐意就如何实现它提供任何建议。

所以事实证明我只是愚蠢,感谢@JB Nizet的评论。

问题中发布的代码是正确的,但我最近在 Angular 应用程序的AppComponent中添加了以下代码段(有点忘记了):

this.authService.currentAuth
  .subscribe(auth => {
    if (!auth) { // navigate to login if the user is not authenticated
      this.router.navigate(['/login']);
    }
  });

这完全是错误的,这就是导致问题的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM