将服务注入到控制器es6语法中

时间:2016-07-28 15:19:13

标签: javascript angularjs ecmascript-6

我正在尝试使用新的angular app语法编写es6。让所有控制器和视图逻辑到位并正常工作,现在我想创建一个简单的共享service。这是我的服务:

var moduleName = 'app.services';
class EventService{
    constructor($http, moment){
        this.$http = $http;
        this.baseUrl = '/api/events';     
    }

    getEvents(){
    return this.$http({method: 'GET', url: this.baseUrl});
    }
}


EventService.$inject = ['$http', 'moment'];

angular.module(moduleName, [])
    .factory('eventSrv', EventService);

export default moduleName;

app.js用于注册模块:

// Import angular
import 'angular';
// Material design css
import 'angular-material/angular-material.css';
// Icons
import 'font-awesome/css/font-awesome.css';
// Animation
import angularAnimate from 'angular-animate';
// Materail Design lib
import angularMaterial from 'angular-material';
// Router
import angularUIRouter from 'angular-ui-router';
//angular messages
import ngMessages from 'angular-messages';
//angular md-table css
import 'angular-material-data-table/dist/md-data-table.min.css';
//angular md-table
import 'angular-material-data-table/dist/md-data-table.min';
//moment
import 'moment';
import 'angular-moment';

//modules
import home from './home/home.module';
import event from './events/event.module';
import sidenav from './sidenav/sidenav.module';
import eventService from './shared/services/events-service';

// Project specific style
import './scss/bootstrap.scss'

// Create module
export const mod = angular.module('app', [
    angularMaterial,
    angularAnimate,
    angularUIRouter,
    'angularMoment',
    'md.data.table',
    eventService,
    home,
    event,
    ngMessages,
    sidenav
]);

mod.config(($stateProvider,$urlRouterProvider) => {
    $stateProvider.state('public', {
        url: "/public",
        abstract: true,
        views: {
            'sidenav': {
                templateUrl: require("./sidenav/sidenav.html"),
                controller: "SidenavController as sidenav"
            }
        }
    });
    $urlRouterProvider.when('', ['$state', '$match', function($state, $match){
        $state.go('public.home');
    }]);

});

我想将服务提供/注入我的家庭控制器,如下所示:

class HomeController {
    constructor($scope, eventSrv) {
        'ngInject';
        var vm = this;
    }
}

HomeController.$inject = ['eventSrv'];
export default HomeController;

家庭模块:

import HomeConfig from './home.config';
import HomeController from './home.controller';
require('./home.scss');

let homeModule = angular.module('app.home', []);

homeModule.config(HomeConfig);
homeModule.controller('HomeController', HomeController);

export default homeModule = homeModule.name

injecting服务eventSrv homecontroller TypeError: Cannot call a class as a function 时,我收到以下错误:

import { Component, OnInit, EventEmitter } from '@angular/core';
import { REACTIVE_FORM_DIRECTIVES } from '@angular/forms';
import { DataTable, Column, Schedule, Growl, Message } from 'primeng/primeng';
import { NameListService } from '../shared/index';

@Component({
  moduleId: module.id,
  selector: 'dash',
  templateUrl: 'dashboard.component.html',
  styleUrls: ['dashboard.component.css'],
  directives: [REACTIVE_FORM_DIRECTIVES, DataTable, Column, Schedule]
})
export class DashboardComponent implements OnInit {

  newName:string = '';
  newLanguage:string = '';
  errorMessage:string;
  names:any[] = [];
  selectedName:any;
  events:any[];
  cols:any[];
  msgs:Message[] = [];

  constructor(public nameListService:NameListService) {
  }

  ngOnInit() {
    this.getNames();
    this.cols = [
      {field: 'id', header: 'ID'},
      {field: 'name', header: 'Name'},
      {field: 'language', header: 'Language'}
    ];
}

  onRowSelect(event) {
    this.msgs = [];
    this.msgs.push({severity: 'info', summary: 'Selected', 
    detail:event.data.name + ' - ' + event.data.language});
}

  getNames() {
    this.nameListService.get()
      .subscribe(
        names => this.names = names,
    error =>  this.errorMessage = <any>error
);
  }

  addName():boolean {
    this.names.push({"name": this.newName, 
    "language": this.newLanguage});
    this.newName = '';
    this.newLanguage = '';
    return false;
  }

}

我的导入或配置出错了什么?

2 个答案:

答案 0 :(得分:3)

eventSrv服务应为service

angular.module(moduleName, [])
    .service('eventSrv', EventService);

factory服务应该与工厂函数一起使用,这些函数由注入器直接调用,ES6类应该是new

答案 1 :(得分:1)

angular.module(moduleName, [])
    .service('eventSrv', ()=> new EventService);