我正在尝试单个$http请求获取我的一个JSON文件并使用我所有控制器中的数据.
我在egghead.io上看到了如何在多个控制器之间共享数据,我还阅读了这个StackOverflow问题:" 在angular.js中的控制器之间共享一个变量 ".
但是,那里的答案不使用该$http模块.使用时$http,控制器没有要处理的数据,并且在收到响应时已经太晚了.
然后我$q.defer在StackOverflow上找到了方法和这个问题:" AngularJS在控制器之间共享异步服务数据 "
在那里发布的解决方案工作正常,但它有两个问题:
$http请求以获得已在另一个控制器中使用的相同数据; 和,then功能.您可以在下面看到我的代码:
controllers.js
'use strict';
/* Controllers */
function appInstallerListCtrl($scope, Data) {
$scope.apps = Data;
}
function appInstallerDetailCtrl($scope, $routeParams, Data) {
$scope.appId = $routeParams.appId;
$scope.apps = Data;
console.log($scope.apps); // <-- then function
console.log(Data); // <-- then function with $vv data returned but I can't access it
for (var i in $scope.apps) // <--- no way, baby!
console.log(i); …Run Code Online (Sandbox Code Playgroud) 我正在使用$ cookieStore模块的服务.它工作正常,但是当单元测试时它会中断,并给出错误:"$ cookieStoreProvider < - $ cookieStore < - filtersService".
该服务看起来像这样:
serviceModule.factory('filtersService', ['$rootScope', '$location', '$cookieStore', function($rootScope, $location, $cookieStore){
return {
getFilters: function(){...}
}
Run Code Online (Sandbox Code Playgroud)
单元测试服务看起来像这样:
describe('filtersService tests', function(){
var filtersService;
beforeEach(module('App.services'));
beforeEach(inject(function(filtersService, urlService, $location){
filtersService = filtersService;
urlService = urlService;
}));
it('test something', inject(function(filtersService, $location){
filtersService.getFilters();
expect(...something...)
}));
});
Run Code Online (Sandbox Code Playgroud)
我在karma测试文件中包含了angular-cookies.
知道为什么代码在运行时有效,但是单元测试失败了吗?
更新:
Karma Config File:
// Karma configuration
// Generated on Sun May 12 2013 16:57:21 GMT+0200 (CEST)
// base path, that will be used to resolve files and exclude
basePath …Run Code Online (Sandbox Code Playgroud) 我试图将服务注入控制器,我收到以下错误:
Error: [$injector:unpr] Unknown provider: employeeServiceProvider <- employeeService
http://errors.angularjs.org/1.3.0-beta.17/$injector/unpr?p0=employeeServiceProvider%20%3C-%20employeeService
at http://localhost:9082/angularJSDemo/js/lib/angular.js:78:12
at http://localhost:9082/angularJSDemo/js/lib/angular.js:3894:19
at Object.getService [as get]
Run Code Online (Sandbox Code Playgroud)
这是代码的plunker.任何帮助,将不胜感激.
我创建了从休息服务接收记录数的资源作为文本.Angular从回答中为每个字符组成一个数组.例如,如果休息答案20,angular将生成数组[2,0].我可以在不转换响应或使用的情况下修复它$http吗?
var resource = angular.module('resource');
resource.factory('RecordResource', ['$resource',
function($resource) {
return $resource('/rest/records/:id', {}, {
count: {
method:'GET',
url: "/rest/records/count",
isArray: false,
responseType: 'text'
}
}
}
]);
Run Code Online (Sandbox Code Playgroud) javascript arrays angularjs angularjs-service angularjs-resource
使用角度1.1.5并需要将urlencoded数据传递给后端.我从这里开始使用解决方案: 如何将数据作为表单数据而不是请求有效负载发布?
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: xsrf
}).success(function () {});
Run Code Online (Sandbox Code Playgroud)
我已经成功地将它嵌入到我的控制器中,但"更清洁"的方式是使用服务和$ resource而不是$ http对象.在本主题的1.1.2之后可以使用transformRequest和$ resource: $ resource transformResponse不工作 但我找不到任何有效的例子.任何人都可以使用$ resource作为服务对象提供上述解决方案的示例吗?
我有一个从外部源检索数据的工厂.一旦我获得数据,我就会使用第二个工厂按特定标准对其进行过滤.
工厂属性已分配给范围.
现在,当我在我的工厂中这样做时,它不会更新范围:
factory.foo = [{id:1,name:'foo'}]; // doesn't work
Run Code Online (Sandbox Code Playgroud)
因此,第二工厂中的过滤器也不起作用
factory.foo = Filter.filter(); // doesn't work
Run Code Online (Sandbox Code Playgroud)
虽然这有效:
factory.foo.push({id:1,name:'foo'}); // works
Run Code Online (Sandbox Code Playgroud)
有没有人知道这是否有意以及为什么会这样,以及如何解决它?
app.factory('Foo',function(Filter) {
var factory = {
foo:[],
getDataForFoo:function() {
factory.foo = Filter.filter(); // doesn't work
//factory.foo = [{id:1,name:'foo'},{id:1,name:'foo'}]; // doesn't work
//factory.foo.push({id:1,name:'foo'}); // works
}
};
return factory;
});
app.factory('Filter',function() {
var factory = {
filter:function() {
var arr = [];
arr.push({id:1,name:'foo'});
return arr;
}
}
return factory;
});
app.controller('MainCtrl', function($scope,Foo) {
$scope.test = 'running';
$scope.foo = Foo.foo; …Run Code Online (Sandbox Code Playgroud) 在AngularJS中处理Firebase的最佳方式肯定必须来自服务,因此它可供整个应用程序中的所有控制器使用.
我只是无法让它工作!...我第一次尝试使用angularFire(new Firebase(url)),希望我可以绑定到服务的范围,但Angular抱怨它不能$watch.
所以我尝试使用angularFireCollection,如下所示:
app.factory('myService', function myService(angularFireCollection) {
var url = 'https://myfirebase.firebaseio.com';
return {
getAll: function(path) {
var ref = angularFireCollection(new Firebase(url + '/' + path));
console.log(ref);
return ref;
},
...
};
});
Run Code Online (Sandbox Code Playgroud)
但是,angularFireCollection是一个包含大量方法等的Object,如果我将它绑定到控制器$ scope我只是得到垃圾.它还抱怨它在我尝试使用之前无法调用Firebase功能(例如Error: Firebase.push failed: second argument must be a valid function.)......任何人都有任何想法我会出错?
看到这个PLUNKER
我是AngularJS的新手,并且有一个加载我的初始用户配置的服务
angular.module('myApp').service('myService', ['$http', function ($http) {
var self = this;
self.user = {};
self.loadConfiguration = function () {
$http.get('/UserConfig').then(function (result) {
self.user = result.data;
});
};
self.loadConfiguration();
}]);
Run Code Online (Sandbox Code Playgroud)
我有一个使用此服务配置的控制器
angular.module('myApp').controller('myController', ['$scope', 'myService', function ($scope, myService) {
var self = this;
// calculation based on service value
self.something = myService.user.something * something else;
}]);
Run Code Online (Sandbox Code Playgroud)
这里的问题是myService.user.something可能是未定义的,因为调用此代码时AJAX请求可能尚未完成.有没有办法在任何其他代码运行之前完成服务?我希望服务函数'loadConfiguration'只运行一次,而不管依赖它的控制器的数量.
我在上搞清楚如何从我的传递参数的麻烦angular controller来
service
#my controller
'use strict';
angular.module('recipeapp')
.controller('recipeCtrl', ['$scope', 'recipeService',
function($scope, recipeService){
$scope.recipeFormData={};
$scope.recipeSave = function(){
recipeService.saveRecipe();
}
}]);
#my service
'use strict';
angular.module('recipeapp').service('recipeService',['$http', function($http){
this.saveRecipe = save;
function save(callback){
//calling external http api
}
}]);
Run Code Online (Sandbox Code Playgroud)
我在这里尝试做的是,$scope.formData从我的表单和控制器获取应该传递给service,根据我的理解,我不能$scope在里面使用service所以我需要找到一种传递$scope.formData给服务的方式
在控制器中,强硬的想法会是,recipeService.saveRecipe($scope.formData);但我不确定如何从服务中收集,
当我改变服务this.saveRecipe(val) = save;它不起作用:(
任何帮助都会得到满足
angularjs angularjs-service angularjs-scope angularjs-controller
我正在尝试创建一个服务来获取json并将其传递给我homeCtrl我可以获取数据但是当它传递给我的homeCtrl它总是返回undefined.我卡住了.
我的服务:
var myService = angular.module("xo").factory("myService", ['$http', function($http){
return{
getResponders: (function(response){
$http.get('myUrl').then(function(response){
console.log("coming from servicejs", response.data);
});
})()
};
return myService;
}
]);
Run Code Online (Sandbox Code Playgroud)
我的家庭控制器:
var homeCtrl = angular.module("xo").controller("homeCtrl", ["$rootScope", "$scope", "$http", "myService",
function ($rootScope, $scope, $http, myService) {
$scope.goData = function(){
$scope.gotData = myService.getResponders;
};
console.log("my service is running", $scope.goData, myService);
}]);
Run Code Online (Sandbox Code Playgroud) angularjs angularjs-service angularjs-factory angularjs-http angular-promise
angularjs ×9
angular-http ×1
angularfire ×1
arrays ×1
firebase ×1
jasmine ×1
javascript ×1
karma-runner ×1
post ×1