javascript - 如何将函数从服务传递到 Controller 并在那里调用 Angularjs 语法 es6?

标签 javascript angularjs

当我尝试在 Controller 中调用 getTodos 函数时,它不返回任何值。我想将 getTodos() 函数返回的值分配给 this.todosthis.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;
<小时/>

最佳答案

尝试:

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

在 Controller 中:

   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 promise 返回为

返回这个。$http.get('/api/todos')

在服务文件中获得 promise

关于javascript - 如何将函数从服务传递到 Controller 并在那里调用 Angularjs 语法 es6?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56113168/

相关文章:

php - 在索引页面上设置 PHP session 以进行 XSRF 检查

javascript - 如何将我的文本溢出转换为列?

不附加到 html 元素的 JavaScript 工具提示

javascript - 在 AngularJS 中销毁和创建指令

javascript - Angular : how to set 'value' different than displayed value in options?

angularjs - 在 AngularJS 中创建自定义对象

javascript - 在不使用 id 的情况下在函数中写入 ajax 成功数据

javascript - Firebase 实时数据库 CORS 问题

javascript - 在实现 Vue-Router 的 VueJS SPA 中实现嵌套的 $refs

angularjs - 使用 Material 使用<md-sidenav>时如何将工具提示放在右边?