Angular 2路由/导航

时间:2016-03-21 02:33:16

标签: angular asp.net-core angular2-routing

我有角度2 ts应用程序,其中路径定义为:

@RouteConfig([
        { path: '/accounts', name: 'Accounts', component: AccountComponent, useAsDefault: true},
        { path: '/transactions', name: 'Transactions', component: TransactionComponent}
])

当我进入浏览器时:http://localhost/网址会随http://localhost/accounts更新并按预期工作,但如果我输入http://localhost/accounts,则会变为http://localhost/accounts/accounts并失败。

有什么问题?

后端-ASP.NET 5,它引用所有未知路径的index.html

   app.Use(async (context, next) =>
        {
            await next();

            if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
            {
                context.Request.Path = "/index.html"; 
                await next();
            }
        });

启动部分:

   public void Configure(IApplicationBuilder app)
    {
        app.UseIISPlatformHandler();

        app.Use(async (context, next) =>
        {
            await next();

            if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
            {
                context.Request.Path = "/index.html"; 
                await next();
            }
        });

        app.UseDefaultFiles();
        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute("spa-fallback", "{*anything}", new {controller = "Home", action = "Index"});
        });

    }

2 个答案:

答案 0 :(得分:1)

<强>更新

我刚注意到你的角度路由器配置中的useAsDefault选项(我之前没有使用过角度2)。我猜这是自动将/ accounts添加到您的URL。试试这个配置

public void Configure(IApplicationBuilder app)
{
    app.UseIISPlatformHandler();

    app.Use(async (context, next) =>
    {
        await next();

        if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
        {
            ctx.Response.Redirect("/");
            return;
        }
    });

    app.UseDefaultFiles();
    app.UseStaticFiles();

}

当您直接在浏览器中输入路径时,它会被asp.net路由引擎捕获。您需要做的是让运行时捕获此路由而不处理它。

app.UseMvc(routes => {
    // maybe you have some other routes.... or not
    routes.Map("spa-fallback", "{*anything}", new {controller = "Home", action="Index"})
});

现在应该发生的是,您的初始页面将由服务器呈现,并且任何其他JS将在该路线上运行。

答案 1 :(得分:0)