【问题标题】:Routing doesn't work for me when doing a hard refresh进行硬刷新时路由对我不起作用
【发布时间】:2017-07-13 22:45:46
【问题描述】:

我在看这个源代码:https://github.com/angular/angular.io/blob/master/public/docs/_examples/toh-5/dart/lib/app_component.dart

当我转到根目录时,我的应用程序似乎会立即路由。

本地主机:8080/

当我在我的应用程序中移动时,路由会更新,但似乎如果我遇到以下情况:localhost:8080/dashboard 在基本情况下,并进行硬刷新,它会失败。它会给我一个404 not found! 错误。

如果我这样做,它只会找到:localhost:8080/#!/dashboard,但这不是传递给我的应用程序的地址。

在 index.html 中我有:<base href="/">

我的 App_Component.dart 文件如下:

import 'package:angular2/angular2.dart';
import 'package:angular2/router.dart';

import 'hero_component.dart';
import 'heroes_component.dart';
import 'dashboard_component.dart';
import 'hero_service.dart';
@Component(
    selector: "my-app",
    directives: const [ROUTER_DIRECTIVES],
    providers: const [HeroService, ROUTER_PROVIDERS],
    templateUrl: "app_component.html")
@RouteConfig(const [
  const Route(
      path: "/dashboard",
      name: "Dashboard",
      component: DashboardComponent,
      useAsDefault: true),
  const Route(
      path: "/detail/:id", name: "HeroDetail", component: HeroDetailComponent),
  const Route(path: "/heroes", name: "Heroes", component: HeroesComponent)
])
class AppComponent {
  String title = "Tour of Heroes";
}

看来我的路由适用于除此之外的所有内容。

我想要的最终状态是:localhost:8080/detail/14,它会打开正确的组件。与浏览整个应用程序时相比,现在在新的站点参考上没有这样做。

【问题讨论】:

    标签: angular angular-dart angular2-routing


    【解决方案1】:

    要切换到HashLocationStrategy,请将提供者更改为

    bootstrap(AppComponent, [
      HeroService, 
      ROUTER_PROVIDERS,
      provide(LocationStrategy, useClass: HashLocationStrategy)
    ])
    

    如果你想使用PathLocationStrategy,你可以使用这个pub serve-wrapper https://pub.dartlang.org/packages/pub_serve_rewrites,它允许使用PathLocationStrategypub serve

    对于部署,您需要配置您使用的网络服务器以支持 HTML5 pushState。

    【讨论】:

    • 完美!效果很好。我正在研究并在这里注意到它:github.com/ng2-dart-samples/router/blob/master/web/main.dart 也是。我最喜欢这个答案。
    • 您还可以使用例如 nginx 作为开发代理,而不是 pub_serve_rewrites。是的,Kasper 在 Angular2 dart 社区中非常活跃。看来他目前正忙于数学学习:-/
    【解决方案2】:

    路由只存在于你的应用程序中,服务器什么都不知道,它只是检查路径/dashboard/detail/14 是否存在不存在的默认页面/文件。

    您必须配置服务器路由器以导航到所有应用程序路由的应用程序 index.html(此处为您的 html 名称)。

    【讨论】:

      【解决方案3】:

      如果localhost:8080/#/dashboard 有效但localhost:8080/dashboard 失败,则表明您使用的是HashLocationStrategy 而不是PathLocationStrategy

      检查您的bootstrap() 函数或其他地方,确保没有注入HashLocationStrategy

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-24
        • 1970-01-01
        • 1970-01-01
        • 2021-06-23
        • 1970-01-01
        • 2016-12-29
        相关资源
        最近更新 更多