标签: angularjs-service

启动新控制器时停止$ timeout

我每隔2秒轮询一次我的数据,以便在页面上更新它们.我的问题是当我访问另一个页面时,超时保持活动状态.当我访问新页面时,如何取消暂停?

function IndexCtrl($scope, $timeout, RestData) {
    $scope.rd = {};

    (function getRestDataFromServer() {
        RestData.query(function(data){
            $scope.rd = data;
            $timeout(getRestDataFromServer, 2000);
        });
    })();
}
Run Code Online (Sandbox Code Playgroud)

//编辑我找到了一个解决方案,但我不确定它是不是一个好的解决方案.当我将超时保存到$ rootScope时,我可以在所有其他控制器中取消它.

function IndexCtrl($scope, $rootScope, $timeout, RestData) {
    $scope.rd = {};

    (function getRestDataFromServer() {
        RestData.query(function(data){
            $scope.rd = data;
            $rootScope.prom = $timeout(getRestDataFromServer, 2000);
        });
    })();
}

function newPageCtrl($scope, $rootScope, $timeout) {
    $timeout.cancel($rootScope.prom); 
}
Run Code Online (Sandbox Code Playgroud)

angularjs angularjs-service

27
推荐指数
2
解决办法
3万
查看次数

如何使用不同模块中具有相同名称的两个AngularJS服务?

假设我有两个AngularJS模块,例如foobar,它们都定义了一个名为的服务baz.

在我的申请中,我依靠他们说:

var app = angular.module('app', [ 'foo', 'bar' ]);
Run Code Online (Sandbox Code Playgroud)

然后我可以尝试使用baz控制器中的服务

app.controller('blaController', [ '$scope', 'baz', function($scope, baz) {
  // ...
}]);
Run Code Online (Sandbox Code Playgroud)

如何定义我想要使用的两种服务中的哪一种?有没有像完全合格的名字?

angularjs angularjs-service angularjs-module

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

AngularJS工厂http返回空

我是第一次尝试AngularJS.我使用工厂从http-get请求获取JSON数据,但在ajax-request完成之前,该对象返回空.

厂:

myDemo.factory('photosFactory', function($http) {
    var photos = [];

    var factory = {};

    factory.getPhotos = function() {
        $http({
            url: 'content/test_data.json',
            method: 'GET'
        }).success(function(data, status, headers, config) {
            photos = data;
            return photos;
        });
    };
    return factory;
});
Run Code Online (Sandbox Code Playgroud)

控制器:

controllers.AppCtrl = function($scope, $location, $http, photosFactory) {
    $scope.photos = [];
    init();
    function init() {
        $scope.photos = photosFactory.getPhotos();
    }
};
Run Code Online (Sandbox Code Playgroud)

这就是我想出来的.当控制器设置$ scope.photos时,该值为空,就像它在填充ajax响应之前返回photos数组一样.

factory http angularjs angularjs-service

23
推荐指数
3
解决办法
4万
查看次数

AngularJS:如何使用ngResource处理成功和错误回调?

文档没有给出任何关于它的想法.

我的REST观点可能会引发错误

$scope.delete = function(index) {
    Transaction.delete({transactionId: $scope.transactions[index].uuid})     
  };
Run Code Online (Sandbox Code Playgroud)

我把上面改为以下

$scope.delete = function(index) {
    Transaction.delete({transactionId: $scope.transactions[index].uuid})
      .success('transaction deleted');
  };
Run Code Online (Sandbox Code Playgroud)

但它失败了

TypeError: Object #<Resource> has no method 'success'
    at Object.TransactionController.$scope.delete (http://localhost:5000/static/app/js/controllers/transactionController.js:26:8)
    at http://localhost:5000/static/app/lib/angular/angular.js:6094:36
Run Code Online (Sandbox Code Playgroud)

我该如何处理successerror场景?

PS我是JavaScript的新手

javascript angularjs angularjs-service

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

如何使用.success和.error在Angularjs中扩展$ q promise

我在AngularJS的自定义服务中编写了这个小代码.

在我的服务中:

        var deferred = $q.defer();
        var promise = deferred.promise;

        deferred.resolve('success');
        deferred.reject('error');

        /* Handle success and error */
        promise.success = function(fn) {

            promise.then(function(response) {

                fn(response);

            });

            return promise;
        };

        promise.error = function(fn) {

            promise.then(null, function(response) {

                fn(response);

            });

            return promise;
        };
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

        promiseService.myPromise()
            .success(function(data){

                $scope.success= data;

            })
            .error(function(data){

                $scope.error = data;

            });
Run Code Online (Sandbox Code Playgroud)

我juste处理承诺的成功和错误($ q服务).我需要在很多其他服务中使用此代码,因此我希望使用自定义直接扩展$ q服务.

所以在我的服务中我想要这样的东西:

    var deferred = myPromiseService.$qCustom.defer();
    var promise = deferred.promise;

    deferred.resolve('success');
    deferred.reject('error');

    return promise;
Run Code Online (Sandbox Code Playgroud)

任何的想法?我发现在Angularjs中扩展过滤器的一些解释我的问题是找到扩展$ q的所有功能并添加我的自定义的好方法.

我从类似的东西开始,处理$ q开箱即用:

angular.module('myApp').service('myPromiseService', function($q){

  $qCustom = $q;  

});
Run Code Online (Sandbox Code Playgroud)

overriding extend promise angularjs angularjs-service

22
推荐指数
2
解决办法
8294
查看次数

将服务用于View AngularJS

我有angularJS服务的问题.

我有简单的服务:

angular.module('mainApp.services', []).factory('AuthService',
function ($http) {
    //var currentUser = null;
    //var authorized = false;

    //AutoLogin for testing
    var currentUser={email: "example@example.com", id: "15"};
    var authorized=true;

    // initial state says we haven't logged in or out yet...
    // this tells us we are in public browsing
    var initialState = false;

    return {
        initialState:function () {
            return initialState;
        },
        login:function (userData) {
            //Call API Login
            currentUser = userData;
            authorized = true;
            initialState = false;
        },
        logout:function () {
            currentUser = null;
            authorized …
Run Code Online (Sandbox Code Playgroud)

angularjs angularjs-service

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

Angularjs - 如何在服务中设置模块值?

我有一个Angular应用程序的以下服务模块.

angular.module('rs.services', [])
  .value('uid', null)

  .factory('login', ['$http', 'uid', function($http, uid) {
    return function(user, pass) {
      var p = $http.post('/login', {"user": user, "pass": pass})
        .success(function(data, status, headers, config) {
          // set uid
        })
        .error(function(data, status, headers, config) {
          // do something
        });

      return p;
    }
  }]);

  // a service that uses uid to authenticate the request
  .factory('userPrefs' ['$http', 'uid', function($http, uid) {
    return function() {
      return $http.post('/user/prefs', {"uid": uid});
    }
  }]);
Run Code Online (Sandbox Code Playgroud)

用户登录后,该login服务返回唯一的会话ID,我想设置模块的uid值以供其他服务调用参考.

我很确定上面的代码不起作用,因为我不能在模块的配置阶段使用值作为依赖项.如何设置服务中的uidlogin并在模块内的其他服务中访问它,或者如果不可能,我如何创建可由这些服务设置/获取的值?

angularjs angularjs-service

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

AngularJS服务在控制器之间传递数据

当使用AngularJS服务尝试在两个控制器之间传递数据时,我的第二个控制器在尝试从服务访问数据时总是收到未定义的.我猜这是因为第一个服务执行$ window.location.href并且我认为这是清除服务中的数据?有没有办法让我将URL更改为新位置,并将数据保留在第二个控制器的服务中?当我运行下面的代码时,第二个控制器中的警报始终是未定义的.

app.js(定义服务的地方)

var app = angular.module('SetTrackerApp', ['$strap.directives', 'ngCookies']);

app.config(function ($routeProvider) 
{
$routeProvider
  .when('/app', {templateUrl: 'partials/addset.html', controller:'SetController'})
  .when('/profile', {templateUrl: 'partials/profile.html', controller:'ProfileController'})
  .otherwise({templateUrl: '/partials/addset.html', controller:'SetController'});
});

app.factory('userService', function() {
var userData = [
    {yearSetCount: 0}
];

return {
    user:function() {
        return userData;
    },
    setEmail: function(email) {
        userData.email = email;
    },
    getEmail: function() {
        return userData.email;
    },
    setSetCount: function(setCount) {
        userData.yearSetCount = setCount;
    },
    getSetCount: function() {
        return userData.yearSetCount;
    }
};
});
Run Code Online (Sandbox Code Playgroud)

logincontroller.js :(控制器1在服务中设置值)

    app.controller('LoginController', function ($scope, $http, $window, userService) {

$scope.login …
Run Code Online (Sandbox Code Playgroud)

angularjs angularjs-service

20
推荐指数
1
解决办法
7万
查看次数

在浏览器控制台中使用Angularjs $ http

我在开发期间在浏览器控制台中测试AngularJS服务以进行快速验证.我注入到服务控制台的方式是在描述这个问题,

var $inj = angular.injector(['myApp']);
var serv = $inj.get('myService');
serv.doSomething();
Run Code Online (Sandbox Code Playgroud)

这与AngularJS 1.0.7完美配合.但是,在升级到1.1.5之后,对于使用$http服务的服务,它不再起作用,不会发送xhr.

我已经测试了$http直接注射,它也不起作用.AngularJS更改日志似乎没有关于此问题的记录.我可以知道这里有什么问题吗?

更新:

似乎AngularJS 1.0.7未压缩版本也不起作用.目前测试的工作版本仅为AngularJS 1.0.7 Minified.

它也适用于未压缩.

angularjs angularjs-service

19
推荐指数
1
解决办法
4089
查看次数

fromJson()中的AngularJS意外标记

以下代码行:

var sid = $cookieStore.get('PHPSESSID');
Run Code Online (Sandbox Code Playgroud)

抛出这个错误:

SyntaxError: Unexpected token m
at Object.parse (native)
at Object.fromJson (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:779:14)
at Object.angular.module.factory.factory.get (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-cookies.js:149:34)
at Object.getAllImages (https://7-september.com/photoslide/js/services.js:29:36)
at new Management (https://7-september.com/photoslide/js/controllers.js:54:18)
at invoke (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2902:28)
at Object.instantiate (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2914:23)
at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:4805:24)
at update (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:14198:26)
at Object.$get.Scope.$broadcast (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:8307:28) 
Run Code Online (Sandbox Code Playgroud)

所以,我在angular.js的第779行放了一个断点.那里的代码是:

777    function fromJson(json) {
778        return isString(json)
779            ? JSON.parse(json)
780            : json;
781    }
Run Code Online (Sandbox Code Playgroud)

json传入的值JSON.parse()是"mnp801fap6kor50trgv4cgk7m2".

我还注意到,传递给该方法的其他内容通常会有两个引号,例如"userName"".

请帮忙.我几个小时就撞了这个头.

或者,如果有人知道使用Angular从cookie中获取php会话ID的更好方法,那也会很棒.(是的,我可以使用jQuery或裸机JS来做,但我更喜欢继续使用Angular).

提前致谢!!!

javascript json angularjs angularjs-service

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