2

在我的 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/login通过粘贴或进入浏览器并按回车键直接导航到登录或注册页面http://localhost:8080/registration将不起作用,因为请求将命中 Spring Boot 应用程序并且由于它没有匹配的映射,因此它将返回 404。

我做的第一件事显然是在 Stackoverflow 上搜索解决方案,大多数答案建议将请求转发到具有匹配映射的根,所以我添加了以下内容Controller

@Controller
public class ViewController {

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

这解决了 404 错误。

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

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

这甚至可能吗?如果是这样,我真的很感激有关如何实现它的任何建议。

4

1 回答 1

1

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

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

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

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

于 2019-03-17T07:53:06.880 回答