BeckiD
BeckiD

Reputation: 315

Undefined service provider angular 1.6 and es6

I'm trying to create rest api for getting for post/get some data using Angular 1.6 and es6. and getting a SylabusService undefined at Component

TypeError: Cannot read property 'save' of undefined

. Service file

'use strict';
import angular from 'angular';

export function SylabusService($resource) {
  'ngInject';
  return $resource('/api/sylabuss/:id', {
      id: '@_id'
    })
  };

. Component file

You can see on line 9, I'm trying to log it but getting back undefined

'use strict';
const angular = require('angular');

const uiRouter = require('angular-ui-router');

import routes from './sylabus.routes';
import SylabusService from './sylabus.service';

export class SylabusComponent {
  /*@ngInject*/
  constructor($scope, SylabusService) {
    console.log(SylabusService); //undefined
      $scope.createSylabus = function(){
        SylabusService.save($scope.newSylaBus.title, function(sylabus){
          console.log(sylabus);
        })
    }
  }
}
SylabusComponent.$inject=['$scope'];
export default angular.module('aSpaApp.sylabus', [uiRouter])
  .config(routes)
  .component('sylabus', {
    template: require('./sylabus.html'),
    controller: SylabusComponent,
    controllerAs: 'sylabusCtrl'
  })
  .factory('service',SylabusService)
  .name;

What I'm doing wrong?

Upvotes: 0

Views: 416

Answers (1)

Matthew Cawley
Matthew Cawley

Reputation: 2818

Your SylabusService is actually called service so add that to the part where you inject your dependencies:

SylabusComponent.$inject=['$scope', 'service'];

Or (perhaps better) name the service SylabusService and inject that:

SylabusComponent.$inject=['$scope', 'SylabusService'];
export default angular.module('aSpaApp.sylabus', [uiRouter])
  .config(routes)
  .component('sylabus', {
    template: require('./sylabus.html'),
    controller: SylabusComponent,
    controllerAs: 'sylabusCtrl'
  })
  .factory('SylabusService',SylabusService) // <-- Name the service here
  .name;

Upvotes: 2

Related Questions