如何为角度2.0 /火花单页面应用程序正确设置客户端路由?

时间:2016-12-12 18:20:34

标签: url angular single-page-application angular2-routing spark-java

我正在使用spark作为我正在开发的angular 2.0应用程序的后端。

我正在服务我的初始index.html,使用spark。

import spark.Spark.*;

public class Browser {

    public static void main(String [] args) {
        staticFiles.location("/public");
        get("/hello/", (req, res) -> "Hello World");
    }

}

这适用于我最初提供的index.html

但是,现在我正在尝试设置一些客户端路由。主要跟随this tutorial跟随一些细微变化。

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MetadataDisplayComponent } from './metadata-display.component';

const routes: Routes = [
    { path : '', redirectTo: '/metadata/', pathMatch: 'full'},
    { path : 'metadata/:path', component: MetadataDisplayComponent}
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
}) 

export class AppRoutingModule{}

现在,如果我将浏览器URL栏导航到“localhost:8050”,那么将提供index.html,客户端代码将在重定向后显示我的“MetadataDisplayComponent”。出于这个原因,我知道我的组件正在被正确导入/使用。

但是,如果我在浏览器URL栏中输入“metadata / foo”,我将收到404错误。我相信这是因为我没有路线

metadata/foo

在我的火花后端。但我希望应用仍像以前一样加载index.html,然后调用客户端的路由来切换相应的组件。

如何设置我的应用以便我可以将网址输入浏览器网址栏,只加载初始index.html,并让客户端路由从那里接管?

EDIT This article似乎很好地表达了我的问题。我需要一种方法来使我的后端的每个请求重定向到相同的index.html文件。

1 个答案:

答案 0 :(得分:0)

我认为您可以从feature added in version 2.5.4 of Spark,自定义404和500错误页面中受益。只需返回重定向到您想要的页面即可。