gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:40:18 25 4
gpt4 key购买 nike

当我尝试在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com