Where should I place code to be used across compon

2019-03-03 08:02发布

问题:

Should it be associated with the app module? Should it be a component or just a controller? Basically what I am trying to achieve is a common layout across all pages within which I can place or remove other components.

Here is what my app's structure roughly looks like:

-/bower_components
-/core
-/login
    --login.component.js
    --login.module.js
    --login.template.html
-/register
    --register.component.js
    --register.module.js
    --register.template.html
-app.css
-app.module.js
-index.html

回答1:

This might be a bit subjective to answer but what I personally do in a components based Angular application is to create a component that will encapsulate all the other components.

I find it particularly useful to share login information without needing to call a service in every single component. (and without needing to store user data inside the rootScope, browser storage or cookies.

For example you make a component parent like so:

var master = {
    bindings: {},
    controller: masterController,
    templateUrl: 'components/master/master.template.html'
};

function masterController(loginService) {

    var vm = this;
    this.loggedUser = {};

    loginService.getUser().then(function(data) {
        vm.loggedUser = data;
    });

    this.getUser = function() {
        return this.loggedUser;
    };
}

angular
    .module('app')
    .component('master', master)
    .controller('masterController', masterController);

The master component will take care of the routing.

index.html:

<master></master>

master.template.html:

<your common header>
<data ui-view></data>
<your common footer>

This way, every component injected inside <ui-view> will be able to 'inherit' the master component like so:

var login = {
    bindings: {},
    require: {
        master: '^^master'
    },
    controller: loginController,
    templateUrl: 'components/login/login.template.html'
};

and in the component controller

var vm=this;
this.user = {};
this.$onInit = function() {
    vm.user = vm.master.getUser();
};

You need to use the life cycle hook $onInit to make sure all the controllers and bindings have registered.

A last trick to navigate between components is to have a route like so (assuming you use ui-router stable version):

.state('home',
{
    url : '/home',
    template : '<home></home>'
})

which will effectively route and load your component inside <ui-view>

New versions of ui-router include component routing.