typescript AngularJS 打字稿路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21796849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:53:40  来源:igfitidea点击:

AngularJS Typescript Routing

angularjstypescript

提问by freschx

Am using the following templateto configure a AngularJS/Typescript web app and receiving the following error.

正在使用以下模板配置 AngularJS/Typescript Web 应用程序并收到以下错误。

The following error is appearing when I run the application:
0x800a139e - JavaScript runtime error: [$injector:modulerr] Failed to instantiate module app due to:

Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

I have checked this threadand ensured that I do indeed have a reference to angular-route.js

我已经检查了这个线程并确保我确实有对 angular-route.js 的引用

app.ts - Easier version to view + index.html

app.ts -更易于查看的版本 + index.html

  /// <reference path="./typings/angularjs/angular.d.ts" />
'use strict';

// Create and register modules
var modules = ['app.controllers','app.directives', 'app.filters', 'app.services'];
modules.forEach((module) => angular.module(module, []));
angular.module('app', modules);

// Url routing
angular.module('app').config(['$routeProvider',
    function routes($routeProvider: ng.IRouteProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'views/MyView.html',
                controller: 'app.controllers.MyController'
            })
            .otherwise({
                redirectTo: '/'
            });
    }
]);

module app {
    export module controllers {}
    export module directives {}
    export module filters {}
    export module services {}

    export interface IController {}
    export interface IDirective {
        restrict: string;
        link($scope: ng.IScope, element: JQuery, attrs: ng.IAttributes): any;
    }
    export interface IFilter {
        filter (input: any, ...args: any[]): any;
    }
    export interface IService {}

    /**
     * Register new controller.
     *
     * @param className
     * @param services
     */
    export function registerController (className: string, services = []) {
        var controller = 'app.controllers.' + className;
        services.push(app.controllers[className]);
        angular.module('app.controllers').controller(controller, services);
    }

    /**
     * Register new filter.
     *
     * @param className
     * @param services
     */
    export function registerFilter (className: string, services = []) {
        var filter = className.toLowerCase();
        services.push(() => (new app.filters[className]()).filter);
        angular.module('app.filters').filter(filter, services);
    }

    /**
     * Register new directive.
     *
     * @param className
     * @param services
     */
    export function registerDirective (className: string, services = []) {
        var directive = className[0].toLowerCase() + className.slice(1);
        services.push(() => new app.directives[className]());
        angular.module('app.directives').directive(directive, services);
    }

    /**
     * Register new service.
     *
     * @param className
     * @param services
     */
    export function registerService (className: string, services = []) {
        var service = className[0].toLowerCase() + className.slice(1);
        services.push(() => new app.services[className]());
        angular.module('app.services').factory(service, services);
    }
}

Am a bit of a TS/Angular newbie so any help would be greatly appreciated.

我是一个 TS/Angular 新手,所以任何帮助都将不胜感激。

Thanks

谢谢

Potential Duplicate: AngularJS + TypeScript: cannot inject $routeProvider

潜在的重复:AngularJS + TypeScript:不能注入 $routeProvider

回答by Scott

You need to make a few changes to that template to get it to work.

您需要对该模板进行一些更改才能使其正常工作。

Full source here

完整来源在这里

First ensure you have the correct references. Including a reference to angular-route.d.ts

首先确保您有正确的参考。包括对angular-route.d.ts

/// <reference path="./typings/angularjs/angular.d.ts" />
/// <reference path="./typings/angularjs/angular-route.d.ts" />

'use strict';

// Create and register modules
var modules = ['app.controllers','app.directives', 'app.filters', 'app.services'];
modules.forEach((module) => angular.module(module, []));

To use the $routeProvideryou must have included the ngRoutemodule in your modules, but because we don't want to register it with angular, because it already exists there, we need to push the module afterwards like this:

要使用$routeProvider你必须ngRoute在你的模块中包含该模块,但是因为我们不想用 angular 注册它,因为它已经存在于那里,我们需要像这样推送模块:

// *** Push ngRoute or $routeProvider won't work ***
modules.push("ngRoute");

angular.module('app', modules);

Then you need to fix the type of $routeProviderfrom ng.IRouteProviderto ng.route.IRouteProvideras that definition is wrong.

然后,你需要修复的类型$routeProvider,从ng.IRouteProviderng.route.IRouteProvider该定义是错误的。

// Url routing
angular.module('app').config(['$routeProvider',
    function routes($routeProvider: ng.route.IRouteProvider) { // *** $routeProvider is typed with ng.route.IRouteProvider ***
        $routeProvider
            .when('/', {
                templateUrl: 'views/MyView.html',
                controller: 'app.controllers.MyController'
            })
            .otherwise({
                redirectTo: '/'
            });
    }
]);

Next TypeScript won't accept empty modules. So having export module controllers {}etc is pointless, because TSC won't include them, and they will be undefined giving errors. Unless you were to define at least one controller, directive, filter and service in your app. But this is solved by simply including null;

Next TypeScript 不接受空模块。所以拥有export module controllers {}etc 是没有意义的,因为 TSC 不会包含它们,并且它们将是未定义的,并给出错误。除非您要在您的应用中定义至少一个控制器、指令、过滤器和服务。但这可以通过简单地包含来解决null;

module app {
    export module controllers { null; }
    export module directives { null; }
    export module filters { null; }
    export module services { null; }

    export interface IController {}
    export interface IDirective {
        restrict: string;
        link($scope: ng.IScope, element: JQuery, attrs: ng.IAttributes): any;
    }
    export interface IFilter {
        filter (input: any, ...args: any[]): any;
    }
    export interface IService {}

    /**
     * Register new controller.
     *
     * @param className
     * @param services
     */
    export function registerController (className: string, services = []) {
        var controller = 'app.controllers.' + className;
        services.push(app.controllers[className]);
        angular.module('app.controllers').controller(controller, services);
    }

    /**
     * Register new filter.
     *
     * @param className
     * @param services
     */
    export function registerFilter (className: string, services = []) {
        var filter = className.toLowerCase();
        services.push(() => (new app.filters[className]()).filter);
        angular.module('app.filters').filter(filter, services);
    }

    /**
     * Register new directive.
     *
     * @param className
     * @param services
     */
    export function registerDirective (className: string, services = []) {
        var directive = className[0].toLowerCase() + className.slice(1);
        services.push(() => new app.directives[className]());
        angular.module('app.directives').directive(directive, services);
    }

    /**
     * Register new service.
     *
     * @param className
     * @param services
     */
    export function registerService (className: string, services = []) {
        var service = className[0].toLowerCase() + className.slice(1);
        services.push(() => new app.services[className]());
        angular.module('app.services').factory(service, services);
    }
}

That should now work and you can register your controllers, filters, services and directives. Such as:

现在应该可以工作了,您可以注册您的控制器、过滤器、服务和指令。如:

module app.controllers
{
    export class testCtrl implements IController
    {
        constructor()
        {
            console.log("Test Controller");
        }
    }
}

app.registerController('testCtrl');

When referencing a controller, or service to use the full name. i.e:

引用控制器或服务时使用全名。IE:

<div ng-controller="app.controllers.testCtrl"></div>

Remember in your html to reference angular-route.jsafter angular.js. i.e:

记住在你的 htmlangular-route.js之后引用angular.js。IE:

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular-route.js"></script>

回答by Prasath Siva

I found my sollution here a link:

我在这里找到了我的解决方案链接

It happens when I tried to include a module dependency that did not exist. This happens due to a number of reasons such as removing a script for index.html for a module but leaving in the module dependency or even misspelling a module dependency. (Turns out my issue was the former.) So this was easy to fix once you knew that.

当我尝试包含不存在的模块依赖项时会发生这种情况。发生这种情况的原因有很多,例如删除模块的 index.html 脚本但留在模块依赖项中,甚至拼错模块依赖项。(事实证明我的问题是前者。)所以一旦你知道这一点就很容易解决。