使用Spring Boot和Angular 2处理URL时出现问题

6
我正在尝试使用Spring Boot作为后端技术和Angular 2作为前端技术来开发一个应用程序,使用Maven管理项目。
Angular 2前端位于项目的“src/main/resources/static”目录中。
当我在浏览器中输入“http://localhost:8080/”时,一切正常:我可以访问Angular 2前端,并且前端可以与REST API完美通信。我的Angular 2路由功能正常:当我在前端上点击链接时,我会进入正确的页面,并且浏览器URL栏显示正确的内容(即“http://localhost:8080/documents”)。
但问题是当我尝试直接在浏览器中编写相同的URL时。Spring接管了前端并说没有映射到“/documents”。
有没有办法告诉Spring Boot只“监听”“/api/*” URL并将所有其他请求“重定向”到前端?
这是我的Spring Controller类:
@RestController
@RequestMapping("/api")
public class MyRestController {

    @Autowired
    private DocumentsRepository documentRepository;

    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/documents/list",
            method = RequestMethod.GET,
            produces = "application/json")
    public Iterable<RfDoc> findAllDocuments() {
        return documentRepository.findAll();
    }

}

这里是主应用程序类:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

这是我的 app.route.ts 文件:

import { provideRouter, RouterConfig }  from '@angular/router';
import { DocumentComponent } from './doc.component';  

const routes: RouterConfig = [
    {
        path: '',
        redirectTo: 'documents',
        pathMatch: 'full'
    },
    {
        path: "documents",
        component: DocumentComponent
    }
];

export const appRouterProviders = [
    provideRouter(routes)
];

有一种方法可以仅监听/api/*。为此,您需要使用过滤器。 - sparrow
我该怎么做呢?我对这个还很陌生... - Eric
1个回答

2

好的,我找到了一个完美的解决方案(至少对于我来说是这样):我通过在URL中添加#符号,将我的位置更改为旧版AngularJS 1.X方式(即http://localhost:8080/#/documents)。

为了实现这个行为,我像这样更改了我的引导程序:

import { bootstrap }      from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';

import { AppComponent }         from './app.component';
import { appRouterProviders }   from './app.routes';
import { AuthService }          from './auth.service';

bootstrap(AppComponent, [AuthService,
    appRouterProviders,
    HTTP_PROVIDERS,
    { provide: LocationStrategy, useClass: HashLocationStrategy }
]);

希望这能帮助到某些人!

不要使用丑陋的哈希标记符号...只需保留HTML5位置策略,并将所有angular2路由重定向到index.html文件。不要重定向所有路由,因为您需要它们用于终点资源(REST控制器)。 - AndroidLover
我该如何进行重定向? - Eric
Eric,请创建一个问题并发布链接,以便我可以粘贴一些代码。 - AndroidLover

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接