当我尝试在控制器中调用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;
答案 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')
在服务文件中获得承诺