我正在将此boilerplate用于angular.js 1.5,我没有使用新的angularjs sintax,并且迷失了如何使用和注入$http
的http请求。
在过去我会使用旧的angularjs服务(MyService
)并在其中注入$ http然后我会在我的控制器中调用MyService.getData()
,但是使用这种新语法我失去了创建一个服务并在其中注入$ http,然后在组件中使用该服务。
这就是模块文件questions.js的样子:
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import questionsComponent from './questions.component';
let questionsModule = angular.module('questions', [
uiRouter
])
.component('questions', questionsComponent)
.name;
export default questionsModule;
questions.component.js
:
import template from './questions.html';
import controller from './questions.controller';
import './questions.scss';
let questionsComponent = {
bindings: {},
template,
controller
};
export default questionsComponent;
最后是questions.controller.js
:
class QuestionsController {
constructor() {
this.name = 'questions';
}
$onInit() {
console.log("$onInit")
}
$onDestroy() {
console.log("$onDestroy")
}
}
export default QuestionsController;
答案 0 :(得分:2)
好的,终于搞定了:
import angular from 'angular';
class HttpService {
static $inject = ['$http','$q']
constructor($http, $q) {
this.$http = $http;
this.$q = $q;
}
getResults() {
console.log("getResults()")
//return this.$http.get('/foo/bar/');
this.$http.get("https://www.reddit.com/r/photoshopbattles/comments/6kl24d/psbattle_bat_carrying_baby.json")
.then(function(response) {
console.log("response", response)
});
}
}
export default HttpService;
在控制器中:
class QuestionsController {
static $inject = ['HttpService']
constructor(HttpService) {
this.name = 'questions';
this.service = HttpService;
}
$onInit() {
console.log("$onInit")
this.service.getResults();
}
$onDestroy() {
console.log("$onDestroy")
}
}
export default QuestionsController;
在模块中:
let questionsModule = angular.module('questions', [
uiRouter,
User
])
.service('HttpService', HttpService)
.component('questions', questionsComponent)
.name;
export default questionsModule;