标签: angularjs-service

如何使控制器等待承诺从角度服务解决

我有一个服务正在向后端发出AJAX请求

服务:

    function GetCompaniesService(options)
    {
        this.url = '/company';
        this.Companies = undefined;
        this.CompaniesPromise = $http.get(this.url);

    }
Run Code Online (Sandbox Code Playgroud)

控制器:

var CompaniesOb = new GetCompanies();
CompaniesOb.CompaniesPromise.then(function(data){
   $scope.Companies = data;
});
Run Code Online (Sandbox Code Playgroud)

我希望我的服务能够处理".then"函数,而不必在我的控制器中处理它,并且我希望能够让我的控制器在服务中的承诺解决之后对服务中的数据进行操作.

基本上,我希望能够像这样访问数据:

var CompaniesOb = new GetCompanies();
$scope.Companies = CompaniesOb.Companies;
Run Code Online (Sandbox Code Playgroud)

随着承诺的解决在服务本身内部处理.

这可能吗?或者是我能够访问该承诺的唯一方法是解决方案来自服务外部吗?

javascript ajax promise angularjs angularjs-service

11
推荐指数
1
解决办法
3万
查看次数

AngularJS - 如何避免使用$ timeout来等待创建元素?

这是一个想法:

所以我试图使用外部库函数在我的ng-repeat所连接的控制器中的DOM中创建一些操作.

最新的jsFiddle工作,但......

http://jsfiddle.net/GeorgiAngelov/KRbdL/150/

所以基本上我得到它与@ BrandonTilley的帮助,但我试图避免使用$ timeout,因为我认为这不是一个可行的解决方案,而是一个黑客.

在@BrandonTilley的帮助下,新的小提琴

添加了onload监听器,我也试图通过getElementById获取新元素或其父元素,但它返回的只是NULL.

http://jsfiddle.net/GeorgiAngelov/KRbdL/143/

问题如下:我在我的控制器中调用了外部函数,它将元素添加到ng-repeat数组中,这在术语中将新元素添加到DOM中.但是,当我在控制器内部时,该元素尚不存在,即使我已将其添加到数组中.

一旦元素实际上被附加到DOM,而不是实际添加到控制ng-repeat的数组中,我如何绑定要调用的外部函数?

问题是我有模板1调用模板2,然后模板2调用template3然后template3调用模板2,我想在template3完成渲染template2后将template3中的元素连接到template2.

我创建了一个链接到template3的指令,我使用了$ last属性,但它仍然无法工作,因为template3加载但我不知道template2何时完成加载.此外,element.ready()甚至没有启动.我也尝试使用$ timeout和删除element.ready进行黑客攻击,但它仍然给了我一个错误,即子元素还没有存在.我不想使用$ timeout,所以我正在为我的问题寻找更实用的解决方案.

另外,当我调用函数来创建一个新的firstlevel元素时,我尝试调用jsPlumb库,但是它给了parentNode undefined.我在addChild函数中对它进行了评论.

在ng-repeat ng-include = template2上的模板3中使用的指令

app.directive('vectorDrawDirective', function($timeout) {
    return function($scope, element, attrs) {
        //angular.element(element).css('color','blue');
        if ($scope.$last === true) {
            element.ready(function() {
            jsPlumb.connect({
                    source: $scope.firstlevel.parent_id,
                    target: $scope.firstlevel.id,
                });
                jsPlumb.repaintEverything();    
        })
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

这是我用来帮助您想象我想要实现的内容的图表(查看右上角的文字)

在此输入图像描述

jsplumb angularjs angularjs-directive angularjs-service angularjs-controller

10
推荐指数
1
解决办法
8880
查看次数

Firebase数据已标准化.我该如何根据这个结构获取一个集合?

我想我已经接近了,我能够打印出属于用户的书籍的ID,但是从firebase书籍参考中一直尝试获取属于用户的书籍列表是不成功的.

我在这里松散地阅读教程:http: //www.thinkster.io/pick/eHPCs7s87O/angularjs-tutorial-learn-to-rapidly-build-real-time-web-apps-with-firebase#item-526e9330d90f99661f00046c

并在此处阅读有关非规范化数据的文档:https: //www.firebase.com/blog/2013-04-12-denormalizing-is-normal.html

如果我想在页面中显示用户,然后是所有书籍,我应该怎么做呢?

火柱结构

FB
|
--user
| |
| --user1
|   |
|   --name: "test name"
|   --email: "test@test.com"
|   --books
|     |
|     "-JFZG3coHOAblHZ7XSjK": true
|     "-KJKJASDIUOPIWE9WEeJ": true
|     "-YtUTRGJLNL876F3SSwS": true
|
--books
  |
  --"-JFZG3coHOAblHZ7XSjK"
  | |
  | --title: "book title 1"
  | --ownerId: "user1"
  |
  --"-KJKJASDIUOPIWE9WEeJ"
  |  |
  |  --title: "book title 2"
  |  --ownerId: "user1" 
  |    
  --"-YtUTRGJLNL876F3SSwS"
  |  |
  |  --title: "book title 2"
  |  --ownerId: "user1" 
Run Code Online (Sandbox Code Playgroud)

视图

<div …
Run Code Online (Sandbox Code Playgroud)

angularjs firebase angularjs-service angularfire

10
推荐指数
1
解决办法
4117
查看次数

AngularJS和Typescript - 注入服务

我一直在写AngularJS应用程序已经有一段时间了,但是Typescript对我来说是新的,然后将AngularJS添加到Typescript中与我习惯的有点不同.

无论如何,两者有什么区别:

app.service('customerDataService', Application.Services.CustomerDataService);

app.service('customerDataService', ['$http', '$q', Application.Services.CustomerDataService]);

控制器TS

module Application {
    export module Services {
        export interface ICustomerDataService {
            getCustomer(id: number): ng.IPromise<Models.ICustomer>;
        }

        export class CustomerDataService implements ICustomerDataService {
            constructor(private $http: ng.IHttpService, private $q: ng.IQService) {
            }

            getCustomer(id: number): ng.IPromise<Models.ICustomer> {
                return this.$http.get('data/Customer.json').then((response) => {
                    return response.data;
                });
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

App TS

var app = angular.module('app', []);

app.value('config', new Application.ApplicationConfig());

app.service('customerDataService', ['$http', '$q', Application.Services.CustomerDataService]);
app.service('customerDataService', Application.Services.CustomerDataService);

app.controller('DefaultController', ['$scope','config', 'customerDataService', Application.Controllers.DefaultController]);
Run Code Online (Sandbox Code Playgroud)

他们似乎都工作.您是否必须明确定义服务的注入?

javascript angularjs typescript angularjs-service

10
推荐指数
1
解决办法
2万
查看次数

Angular - TypeError:XX不是函数

也许我错过了某种属性,但是我正在关注这个项目,我在控制器中遇到了这个错误.

TypeError: loginService.signin is not a function
Run Code Online (Sandbox Code Playgroud)

这是我的controller.js

angular.module('appcontrollers', []).controller('LoginController', ['$rootScope', '$scope', '$http', '$location', '$localStorage', 'loginService',  
        function ($rootScope, $scope, $http, loginService) {

        $scope.signin = function() {

            console.log("username: " + $scope.username);
            console.log("pass: " + $scope.password);

            var formData = {
                username: $scope.username,
                password: $scope.password
            };

            // ERROR IN THIS LINE
            loginService.signin(formData, function(res) {
                console.log("asdf");
                if (res.type == false) {
                    console.log(res.data);
                } else {
                    $localStorage.token = res.data.token;
                    console.log("Window location /");
                }
            }, function() {
                $rootScope.error = "Error en el logueo del …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angularjs-service angularjs-scope angularjs-factory

10
推荐指数
1
解决办法
3万
查看次数

AngularJS在连接或断开连接到firebase时更新服务值

我希望在连接或断开连接到firebase服务器时更改图标颜色.我到目前为止:

HTML

<button class="button button-icon ion-cloud" ng-style="dbConnectedStyle"></button>
Run Code Online (Sandbox Code Playgroud)

调节器

firebaseRef.$loaded().then( function() {
  $scope.dbConnectedStyle = {'color': dbConnectStatus.color};
}
Run Code Online (Sandbox Code Playgroud)

服务

.service('dbConnectStatus', function(firebaseRef){
  var status = false;
  var color = 'transparent';
  var connectedRef = firebaseRef.child(".info/connected");
  connectedRef.on("value", function(snap) {
    status = snap.val();
    if (status) {
      color = 'lightgrey';
      console.log("Connected to DB (" + color + ")" );
    } else {
      color = 'transparent';
      console.log("Disonnected to DB (" + color + ")" );
    }
  });
  return {
    'boolean': status,
    'color': color
  }
})
Run Code Online (Sandbox Code Playgroud)

它第一次改变颜色.但是当它断开连接时它没有改变......似乎它不是双向绑定到服务.我该如何实现这一目标?


UPDATE

尝试将服务作为对象进行引用而不是执行基元分配,如 …

angularjs firebase angularjs-service firebase-realtime-database

10
推荐指数
1
解决办法
613
查看次数

在控制器之间共享异步数据而不会发出多个请求

我正在尝试单个$http请求获取我的一个JSON文件并使用我所有控制器中的数据.

我在egghead.io上看到了如何在多个控制器之间共享数据,我还阅读了这个StackOverflow问题:" 在angular.js中的控制器之间共享一个变量 ".

但是,那里的答案不使用该$http模块.使用时$http,控制器没有要处理的数据,并且在收到响应时已经太晚了.

然后我$q.defer在StackOverflow上找到了方法和这个问题:" AngularJS在控制器之间共享异步服务数据 "

在那里发布的解决方案工作正常,但它有两个问题:

  1. 每个控制器将触发$http请求以获得已在另一个控制器中使用的相同数据; 和,
  2. 如果我试图操纵收到的数据我有一个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)

angularjs angularjs-service angularjs-scope

9
推荐指数
2
解决办法
6839
查看次数

未知的提供商CookieStore

我正在使用$ 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)

jasmine angularjs angularjs-service karma-runner

9
推荐指数
1
解决办法
3万
查看次数

AngularJS [$ injector:unpr]未知的提供者

我试图将服务注入控制器,我收到以下错误:

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.任何帮助,将不胜感激.

angularjs angularjs-service

9
推荐指数
1
解决办法
4万
查看次数

响应类型为text/plain的Angular资源总是生成一个字符串数组

我创建了从休息服务接收记录数的资源作为文本.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

9
推荐指数
1
解决办法
6307
查看次数