javascript - 基于 Angular 组件的方法和在 Router 中使用 resolve

标签 javascript angularjs

所以我在 Angular 上使用基于组件的方法,假设我有一个名为 <home></home>; 的指令

import template from  './home.html';
import controller from './home.controller.js';

angular.module('myApp')
   .directive('home', homeDirective);

let homeDirective = () => {
    return {
        restrict: 'E',
        template, 
        controller,
        controllerAs: 'vm',
        bindToController: true
    };
};

现在我可以使用组件 <home></home>在我的路由中如下:

angular.module('myApp')
    .config(($routeProvider) => {
        $routeProvider.when('/', {
            template: '<home></home>'
        })
    })

我真的很喜欢这种方法,但是对于“旧”方法,我习惯于在我的 routeconfig 中使用“resolve”来仅在解决 promise 时才呈现组件:

angular.module('myApp')
    .config(($routeProvider) => {
        $routeProvider.when('/', {
            templateUrl: './home.html',
            controller: './home.controller.js',
            resolve: {
            message: function(messageService){
                return messageService.getMessage();
            }
        })
    })

问题

我如何在 Angular 中使用 resolve 和基于组件的方法?阿杰

最佳答案

有一个已关闭的问题:support resolve option for directives .

结论是他们不希望异步加载任意指令,因为这会导致太多闪烁。

The good news is that Angular 2 supports this (and much more) at the DI layer in a way that's cohesive and doesn't introduce a ton of additional complexity.

在 Angular 1.x 中,您可以使用从何处获取消息的一些信息来为指令添加属性,并在您的 Controller 中处理异步加载。这样你也可以显示一些漂亮的加载器屏幕。

angular.module('myApp')
    .config(($routeProvider) => {
        $routeProvider.when('/', {
            template: '<home my-datasource="feed1"></home>'
        }).when('/other', {
            template: '<home my-datasource="feed2"></home>'
        })
    })
    .factory('DataSources', (messageService) => {
        return {
            feed1: messageService.getMessage,
            feed2: messageService.getError
        };
    });

或者,如果您希望消息 始终来自同一源,您可以将messageService.getMessage().then(...) 刻录到您的 Controller 中。

如果您不希望指令在 promise 解析之前完全可见,您可以引入一个最初设置为 false 的范围变量,然后在解析时将其设置为 true,例如:

app.controller('HomeController', ($scope, messageService) => {
   $scope.loaded = false;
   messageService.getMessage().then(message => {
       ...
       $scope.loaded = true;
   });
   ...
});

并隐藏指令,直到在根元素处使用 ng-if="loaded" 加载。是的,用户代码有点太多了,但你至少可以控制一切。

关于javascript - 基于 Angular 组件的方法和在 Router 中使用 resolve,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34044741/

相关文章:

javascript - 仅在 html 中插入图像一次

javascript - webview 加载网页,但一些内容在加载后消失(Android Studio)

javascript - Jasmine .toThrow 错误

javascript - 如何在 CSS 中使用 Javascript 变量?

javascript - 如何在SAPUI5应用程序 View Controller 中正确包含三个js(外部库)?

angularjs - 这么多缺失的部分。接下来看哪里?

angularjs - 为什么在页面加载时触发 $locationChangeStart?

javascript - CORS 服务器端与客户端?为什么一个有效,而另一个却无效?

javascript - Konva.js 中的中心旋转箭头

JavaScript 在一行中设置命名函数的原型(prototype)