Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 角度-在控制器函数中使用$http服务_Angularjs_Angularjs Service - Fatal编程技术网

Angularjs 角度-在控制器函数中使用$http服务

Angularjs 角度-在控制器函数中使用$http服务,angularjs,angularjs-service,Angularjs,Angularjs Service,伙计们——在我继续的角度冒险中,我遇到了一个问题,$http.get对我有效,而$http.post对我无效。很明显,这是一个范围问题(即,我的控制器函数可以看到“$http”,但它的一个函数不能看到。以下是我目前的代码: var app = angular.module('docManager', []); app.controller('DocManCtrl', ['$http', DocManCtrl]); function DocManCtrl($http){ var self =

伙计们——在我继续的角度冒险中,我遇到了一个问题,$http.get对我有效,而$http.post对我无效。很明显,这是一个范围问题(即,我的控制器函数可以看到“$http”,但它的一个函数不能看到。以下是我目前的代码:

var app = angular.module('docManager', []);
app.controller('DocManCtrl', ['$http', DocManCtrl]);

function DocManCtrl($http){
  var self = this;
  $http.get('http://localhost:3000/documents').success(function(data){
    self.documents = data;
    }).error(function(){
    console.log('Error: could not GET documents');
  });
}

DocManCtrl.prototype.addDoc = function(){
  var self = this;
  self.documents.push({filename: this.filename, category: this.category});
  $http.post('http://localhost:3000/documents', self.documents).success(function(data){
  console.log('document posted.');
  }).error(function(){
  console.log('document not posted');
  });
};
我的HTML页面通过$http.get方法显示所有记录,但当我尝试将数据发布到后端时,控制器的“addDoc”方法(由表单提交触发)导致“$http未定义”错误。因此--如何将$http注入我的addDoc方法

谢谢!
Bryan

如果您真的想将控制器与实例方法一起使用,您必须在self上创建对注入服务的引用:

var-app=angular.module('docManager',[]);
app.controller('DocManCtrl',['$http',DocManCtrl]);
函数DocManCtrl($http){
var self=这个;

self.\u http=$http;//一个更干净的解决方法是不使用控制器上的原型,并将addDoc中的逻辑移动到一个注入了$http的服务中,而不是处理范围问题,这可能更类似于您在web上看到的其他角度代码。