如何将函数从服务传递到控制器,并在其中调用Angularjs语法es6?

时间:2019-05-13 13:15:24

标签: javascript angularjs

当我尝试在控制器中调用getTodos函数时,它不返回任何值。我想将this.todos函数返回的值赋给getTodos()this.todos返回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 个答案:

答案 0 :(得分:1)

尝试:

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')

在服务文件中获得承诺