如何使用 TypeScript 为 stateprovider 配置控制器

How to configure controllers for stateprovider with TypeScript

假设我有以下简化的控制器:

module App {
    "use strict";

    export class StoreDetailController {
        constructor() {
            alert("Detail-Controller");
        }
    }
}

UI-Router配置如下(简化):

var app = angular.module("app", ["ui.router"])
    .config(($stateProvider, $locationProvider, $urlRouterProvider) => {
        $urlRouterProvider.otherwise("/");
        $stateProvider.state("store", {
            url: "/Store",
            templateUrl: "/Store/Partial?name=Layout"
        });
        $stateProvider.state("store.Detail", {
            url: "/Details/:id",
            templateUrl: "/Store/Partial?name=Details",
            controller: StoreDetailController
        });
        $locationProvider.html5Mode(true);
    });

当我从应用程序的起始页进入详细信息页时,一切正常(出现消息框)。但是,如果我在详细信息页面上重新加载浏览器或将嵌套的 url 粘贴到新选项卡中,则不会调用控制器并且不会引发错误。

如果我直接在配置中 'declare' 控制器,一切似乎也能正常工作,例如:

//...
$stateProvider.state("store.Detail", {
    url: "/Details/:id",
    templateUrl: "/Store/Partial?name=Details",
    controller: () => alert("This is called every time");
});
//...

配置控制器在重新加载或进入嵌套 url 时使用的状态提供程序的正确方法是什么?

在这种情况下,最值得怀疑的,也是罪魁祸首,是 HTML 设置不当。

浏览器只需要知道什么是所有相对导航的base href。如果我们直接导航到 https://domain/app/Store/Partial?name=Layout,这可能会让它感到困惑 (对于浏览器)。要解决它,我们只需要设置元素 <base>

<base href="/" />

检查此 Q & A about html5mode,工作 example/plunker

有趣的是 Angular 的 $htmlProvider 还有其他方式,就是它的配置:

$locationProvider.html5Mode({
   enable: true,
   requireBase: false.
});

查看文档:

$locationProvider

关于配置的小引用:

  • enabled – {boolean} – (default: false) If true, will rely on history.pushState to change urls where supported. Will fall back to hash-prefixed paths in browsers that do not support pushState.
  • requireBase - {boolean} - (default: true) When html5Mode is enabled, specifies whether or not a tag is required to be present. If enabled and requireBase are true, and a base tag is not present, an error will be thrown when $location is injected. See the $location guide for more information
  • rewriteLinks - {boolean} - (default: true) When html5Mode is enabled, enables/disables url rewriting for relative links.