使 2 个州共享决心的一部分

Makes 2 states share a part of resolve

我定义了两种状态如下:

app.config(['$stateProvider', function ($stateProvider) {
    $stateProvider
        .state('edit', {
            url: '/edit/{id}',
            templateUrl: '/htmls/h1.html',
            controller: 'SameCtrl',
            onEnter: ...sameOnEnter...
            resolve: {
                ...commonResolve...
            }
        })
        .state('addinEdit', {
            url: '/addin/edit/{id}',
            templateUrl: '/htmls/h2.html',
            controller: 'SameCtrl',
            onEnter: ...sameOnEnter...
            resolve: {
                special: [ ... ],
                ...commonResolve...
            }
        })
}])

所以他们共享相同的控制器,相同的 onEnter,并且他们有一个 很长 resolve 的公共部分(实际上是一个 的解析:first: function (...){...}, second: function (...){...}, ...)。有谁知道如何重写它们,这样我就不必写 commonResolve 两次?

我没有经验 angularjs 但我找到了解决方案, 您可以通过父级 属性.

指定状态的父级
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider
    .state('edit', {
        url: '/edit/{id}',
        templateUrl: '/htmls/h1.html',
        controller: 'SameCtrl',
        onEnter: ...sameOnEnter...
        resolve: {
            ...commonResolve...
        }
    })
    .state('addinEdit', {
        url: '/addin/edit/{id}',
        templateUrl: '/htmls/h2.html',
        parent : 'edit'
    })
}])

只需为解析器创建一个函数:

    app.config(['$stateProvider', function ($stateProvider) {

        resolverFunction.$inject = ['resolverA', 'resolverB'];
        function ResolverFunction(myService1, myService2) {
            return 'something';
        }

        resolverAFunction.$inject = ['resolverC'];
        function resolverAFunction(resolverC) {
            return 'anything';
        }

        resolverBFunction.$inject = ['resolverC'];
        function resolverBFunction(resolverC) {
            return 'something else';
        }

        resolverCFunction.$inject = ['service'];
        function resolverCFunction(service) {
            return 'something else';
        }


        $stateProvider
            .state('edit', {
                url: '/edit/{id}',
                templateUrl: '/htmls/h1.html',
                controller: 'SameCtrl',
                onEnter: ...sameOnEnter...
                resolve: {
                   commonResolver: resolverFunction,
                       resolverA: resolverAFunction,
                       resolverB: resolverBFunction,
                       resolverC: resolverCFunction,

                }
    })
        .state('addinEdit', {
            url: '/addin/edit/{id}',
            templateUrl: '/htmls/h2.html',
            controller: 'SameCtrl',
            onEnter: ...sameOnEnter...
            resolve: {
               special: [ ... ],
               commonResolver: resolverFunction,
                resolverA: resolverAFunction,
                resolverB: resolverBFunction,
                resolverC: resolverCFunction,

            }
    })
    }])