Как передать функции из сервиса в контроллер и вызвать его там с помощью синтаксиса Angularjs es6? - PullRequest
0 голосов
/ 13 мая 2019

Когда я пытаюсь вызвать функции getTodos в контроллере, он не возвращает никакого значения.Я хочу присвоить this.todos значение, возвращаемое функцией getTodos().this.todos return null

/* ----- todo/todo.service.js ----- */
   class TodosController {
   constructor(TodoService) {
    'ngInject'
    this.ArtistsListService = ArtistsListService;
   }

    $onInit() {
      this.todos = null;
      this.TodoServiceService.getTodos().then(response => 
 this.todos = response);
      console.log(this.todos);
    }
}

export default TodosController;`

/* ----- todo/todo.service.js ----- */
   export class TodoService {
  constructor($http) {
    'ngInject';
    this.$http = $http;
  }
  getTodos() {
    return this.$http.get('/api/todos').then(response => 
 response.data);
  }
}

/* ----- todo/todo.module.js ----- */
 import angular from 'angular';
 import { TodoComponent } from './todo.component';
  import { TodoService } from './todo.service';
 import './todo.scss';

 export const TodoModule = angular
  .module('todo', [])
  .component('todo', TodoComponent)
  .service('TodoService', TodoService)
  .name;

1 Ответ

1 голос
/ 13 мая 2019

Попробуйте:

export class TodoService {
  constructor($http) {
    'ngInject';
    this.$http = $http;
  }
  getTodos() {
    return this.$http.get('/api/todos');
  }
}

и в контроллере:

   class TodosController {
   constructor(TodoService) {
    'ngInject'
    this.ArtistsListService = ArtistsListService;
   }

    $onInit() {
      this.todos = null;
      this.TodoServiceService.getTodos().then(response => 
        {
           this.todos = response.data;
           console.log(this.todos);
        },
        (error) => { console.error(error) }
       );

    }
}

export default TodosController;

Вам нужно вернуть http обещание как

return this.$http.get('/api/todos')

в служебном файле, чтобы получить обещание

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...