标签: angularjs-factory

TypeScript + AngularJS v1:将角度工厂重写为TypeScript

我想知道如何将以下工厂重写为TypeScript代码.这是原始代码:

app.factory('errorInterceptor', function ($q) {
    return {
        responseError: function (response) {
            console.error("Error: " + response.statusText);
            return $q.reject(response);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试了以下内容:

 export class errorInterceptor {
    constructor(private $q:ng.IQService) {

    }

    public responseError(response:any){
        console.error("Error: " + response.statusText);

        return this.$q.reject(response);
    }

    public static getFactory(){
        return  errorInterceptor;
    }
}

app.factory('errorInterceptor',errorInterceptor.getFactory());
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

Provider 'errorInterceptor' must return a value from $get factory method.
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

interceptor angularjs typescript angularjs-factory

6
推荐指数
1
解决办法
260
查看次数

在使用AngularJS的工厂中,$ location.path不会更改

我的工厂看起来像:

'use strict';

angular.module('myApp')
  .factory('httpInterceptor',['$q','$location', '$rootScope', function($q, $location, $rootScope){
    return {
      response: function(response) {

        if(response.success === false) {
console.log("Redirecting");
            $location.path('/login');
            return $q.reject(response);
        }

        return response || $q.when(response);
      }
    }
}]);
Run Code Online (Sandbox Code Playgroud)

它吐出日志,但不会改变路径.我该怎么做才能实现这一目标?

angularjs angularjs-routing angularjs-factory

5
推荐指数
2
解决办法
6336
查看次数

AngularJS - Factory - TypeError:无法读取未定义的属性'getSpec'

我从AngularJS开始,我在尝试使用控制器中的工厂时遇到了一些问题.

我有以下工厂

angular.module('testingApp')
  .factory('factoryService', function ($http) {
    // Service logic
    var getSpec = function(p) {
      return $http.get('http://someurl//?p=' + p);
    };
    return {
      getSpec: getSpec  
    };
  });
Run Code Online (Sandbox Code Playgroud)

然后我尝试从控制器消耗它,如下所示

angular.module('testingApp')
  .controller('ServiceincientsCtrl',[ function (factoryService,$scope) {
   console.log('Starting Service Incident Controller');
    factoryService.getSpec('AAA').then(function(response){
        $scope.result = response.data;
    }, function(error){
        console.log('opsssss' + error);
    });

  }]);
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试运行它时,我收到以下消息

TypeError: Cannot read property 'getSpec' of undefined
Run Code Online (Sandbox Code Playgroud)

我不知道我错过了什么,它应该是一个新手错误,我用谷歌搜索它,我尝试了许多具有相同结果的例子.

我做错了什么想法?

谢谢!

angularjs angularjs-factory

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

如何用angularjs中的2个相同控制器制作原型?

在我的应用程序中,我有两个几乎相同的控制 很多功能都是一样的,所以我想把它们原型化.这是控制器#1:

c2gcontroller.js

angular.module('c2gyoApp')
  .controller('C2gCtrl', function($scope) {
    // some unique stuff
    $scope.feeDay = 59;
    ...
    // the identical functions
    $scope.getMinutes = function(minutes) {
      var duration = moment.duration(minutes, 'm');
      return duration.minutes();
    };
    ...
  });
Run Code Online (Sandbox Code Playgroud)

和控制器#2:

c2gbcontroller.js

angular.module('c2gyoApp')
  .controller('C2gbCtrl', function($scope) {
    // some unique stuff
    $scope.feeDay = 89;
    ...
    // the identical functions
    $scope.getMinutes = function(minutes) {
      var duration = moment.duration(minutes, 'm');
      return duration.minutes();
    };
    ...
  });
Run Code Online (Sandbox Code Playgroud)

我试过投入$scope.getMinutes工厂:

smfactory.js

angular.module('c2gyoApp')
  .factory('smfactory', function() {
    return {
      getHours: function(minutes) {
        var duration …
Run Code Online (Sandbox Code Playgroud)

dependency-injection angularjs angularjs-service angularjs-factory angularjs-provider

5
推荐指数
1
解决办法
750
查看次数

如何将对象推入JavaScript Prototype内部的数组?

我有一个Angular Factory,其工作是保存特殊对象并在以后检索它们.
(用于在切换视图时保存用户工作流程).

基本上我需要保存带有名称的对象以及一组标签.我的问题是将标签保存到数组部分.

Prototype构造函数:

// define the TagsObject constructor function
var TagsObject = function(name, tag) {
    this.name = name;
    this.tags = [].push(tag);
    return this;
};
Run Code Online (Sandbox Code Playgroud)

完整的工厂代码:

.factory('TagFactory', [function() {

    // Init TagFactory:
    var tagContainers = [];

    // define the TagsObject constructor function
    var TagsObject = function(name, tag) {
        this.name = name;
        this.tags = [].push(tag);
        return this;
    };

    console.log('tagFactory');
    console.log(TagsObject);

    var saveTags = function(name, tag) {

        tagContainers.push(new TagsObject(name, tag));

        console.log('saveTags:');
        console.log(tagContainers);
    };

    var getTags = function(name) {
        console.log(name);
        return this; …
Run Code Online (Sandbox Code Playgroud)

javascript prototype angularjs angularjs-service angularjs-factory

5
推荐指数
0
解决办法
1388
查看次数

如何使用不与使用它的控制器共享其值的服务对象

我们假设我创建了一个工厂,服务或提供者对象

myApp.factory('myService', function() {
  return {
    counter: 0,
    increment: function() {
      console.log('counter: ' + (this.counter++))
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

假设我有一个依赖它的控制器

myApp.controller('myCtrl', function(myService) {
  $scope.incr = function() {
    myService.increment();
  };
}
Run Code Online (Sandbox Code Playgroud)

我将此控制器应用于html的不同部分

<div ng-controller="myCtrl">
  <button ng-click="increment()">increment</button>
</div>
...
<div ng-controller="myCtrl">
  <button ng-click="increment()">increment</button>
</div>
Run Code Online (Sandbox Code Playgroud)

现在,当我点击每个按钮时,计数器是通用的,它会变为0,1,2,3 ......

如何编写工厂,服务或提供程序,以便每个控制器获取服务对象的不同副本?

angularjs angularjs-service angularjs-factory angularjs-provider

5
推荐指数
1
解决办法
667
查看次数

这个AngularJS工厂的例子究竟如何?有些疑惑

我是AngularJS的绝对新手,我正在研究它.我怀疑与Angular 工厂的使用有关.

我知道工厂是用于根据要求创建对象的模式.

所以在这个例子中有以下代码:

// Creates values or objects on demand
angular.module("myApp")     // Get the "myApp" module created into the root.js file (into this module is injected the "serviceModule" service
.value("testValue", "AngularJS Udemy")

// Define a factory named "courseFactory" in which is injected the testValue
.factory("courseFactory", function(testValue) {
    // The factory create a "courseFactory" JSON object;
    var courseFactory = {
            'courseName': testValue,    // Injected value
            'author': 'Tuna Tore',
             getCourse: function(){     // A function is a valid field of a …
Run Code Online (Sandbox Code Playgroud)

javascript json javascript-framework angularjs angularjs-factory

5
推荐指数
1
解决办法
504
查看次数

用工厂获取数据json

我正在尝试学习如何在工厂内获取数据.目前我正在使用控制器获取数据

factory.js

angular
    .module('app')
    .factory('Product', ['$http', function($http){
        return{
            get: function(){
                return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
                    return response.data;
                });
            }
        };
    }])
Run Code Online (Sandbox Code Playgroud)

细节poduct.js

    angular
        .module('app')
        .controller('productDetailsCtrl',['$scope','$stateParams', 'Product', function($scope,$stateParams,Product){
            $scope.id=$stateParams.id;
            Product.get().then(function(data) {
                $scope.singleItem = data.filter(function(entry){
                    return entry.id === $scope.id;
                })[0];
            });
}]);
Run Code Online (Sandbox Code Playgroud)

产品detail.html

<a href="{{singleItem.url}}">
<p>{{singleItem.id}}</p>    
<p>{{singleItem.name}}</p>
<img src="{{singleItem.image}}" alt="{{singleItem.name}}">  
</a>    
Run Code Online (Sandbox Code Playgroud)

但是当我更改代码以在工厂内移动fecthing时就像这个factory.js

return{
            get: function(){
                return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
                    return response.data;
                });
            },
            find: function(){
                return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
                    var singleItem = data.filter(function(entry){
                        return entry.id === id;
                    })[0];
                });
            }
        };
Run Code Online (Sandbox Code Playgroud)

细节product.js

angular
    .module('app')
    .controller('productDetailsCtrl',['$scope','$stateParams', 'Product', function($scope,$stateParams,Product){
        Product.find($stateParams.product,function(singleItem){
            $scope.singleItem …
Run Code Online (Sandbox Code Playgroud)

javascript json promise angularjs angularjs-factory

5
推荐指数
1
解决办法
77
查看次数

AngularJS $资源和缓存工厂

我已经使用自定义函数和参数实现了角度$资源,如下所示:

.factory('CandidateService', ['$resource', function ($resource) {
    return $resource("api/:action/:id", {},
    {
        'getCandidates': { method: "GET", params: { action: "Candidate" }, isArray: true },
        'getCandidate': { method: 'GET', params: { action: "Candidate", id: "@id" } }
    });
}]);
Run Code Online (Sandbox Code Playgroud)

我在控制器中使用它如下: -

.controller('Controller', ['CandidateService', function ($scope, CandidateService) {
  $scope.candidateList = [];

  CandidateService.getAll(function (data) {
    $scope.candidateList = data;   
  });
}]);
Run Code Online (Sandbox Code Playgroud)

这工作绝对正常.现在我需要将来自api的数据缓存到CandidateService Factory中,这样就不会在控制器之间移动eveytime.

所以我想我会做如下事情: -

.factory('CandidateService', ['$resource', function ($resource) {
    var Api = $resource("api/:action/:id", {},
    {
        'getCandidates': { method: "GET", params: { action: "Candidate" }, isArray: …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angularjs-factory

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

应用程序启动时初始化角度服务(工厂)

在我的Angular应用程序中,我添加了跟踪功能,它应该作为单独的插件工作,因此如果包含在HTML Angular中的脚本应该创建服务并初始化(运行)它.插件是服务,因为它具有强制依赖性$rootScope.为了实现我选择使用Angular工厂,就像(代码在myservice.js):

angular.module('app').factory('mysevice', ['$rootScope', '$interval', serviceFunc]);

function serviceFunc($rootScope, $interval) {

    return {
        run: function () { ... } 
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我有问题如何立即初始化它.我的解决方案是增强Angular app run功能(代码在myservice.js中):

window.app.run(['mysevice', function (srvc) {
        srvc.run();
    }]);
Run Code Online (Sandbox Code Playgroud)

app在单独的主app.js文件中定义的位置如下:

var app = window.app = angular.module('app', [...]);
app.run(['$state', 'breeze', ...,
function ($state,  breeze, ...) { ..real initialization..  }
Run Code Online (Sandbox Code Playgroud)

代码工作正常.这两个主要runrun用于myservice通话的罚款.应用程序与服务一起运行良好,但代码看起来很难看,特别是将应用程序存储在全局窗口对象中并组播该run功能.

是否有更好的方法来执行Angular服务并在应用程序启动后立即初始化它与其他一些Angular服务依赖项.

javascript angularjs angularjs-service angularjs-factory

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