• Stars
    star
    561
  • Rank 79,400 (Top 2 %)
  • Language
    JavaScript
  • Created almost 12 years ago
  • Updated about 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Easily add spinners or general request tracking to your angular app

angular-promise-tracker

Version: 2.0

(note to users using version 1.x: upgrading has many breaking changes, see the CHANGELOG.)

Build Status

Small, feature filled library used to easily add spinners or general promise/request tracking to your angular app.

Quick Start

The basic idea: each time we add one or more promises to an instance of a promiseTracker, that instance's active() method will return true until all added promises are resolved. A common use case is showing some sort of loading spinner while some http requests are loading.

Play with this example on plunkr

$ bower install angular-promise-tracker
<body ng-app="myApp" ng-controller="MainCtrl">
  <div class="my-super-awesome-loading-box" ng-show="loadingTracker.active()">
    Loading...
  </div>
  <button ng-click="delaySomething()">Delay Something</button>
  <button ng-click="fetchSomething()">Fetch Something</button>

  <script src="angular.js"></script>
  <script src="promise-tracker.js"></script>

  <!-- optional for $http sugar -->
  <script src="promise-tracker-http-interceptor.js"></script>
</body>
angular.module('myApp', ['ajoslin.promise-tracker'])
.controller('MainCtrl', function($scope, $http, $timeout, promiseTracker) {
  //Create a new tracker
  $scope.loadingTracker = promiseTracker();

  //use `addPromise` to add any old promise to our tracker
  $scope.delaySomething = function() {
    var promise = $timeout(function() {
      alert('Delayed something!');
    }, 1000);
    $scope.loadingTracker.addPromise(promise);
  };

  //use `tracker:` shortcut in $http config to link our http promise to a tracker
  //This shortcut is included in promise-tracker-http-interceptor.js
  $scope.fetchSomething = function(id) {
    return $http.get('/something', {
      tracker: $scope.loadingTracker
    }).then(function(response) {
      alert('Fetched something! ' + response.data);
    });
  };
});

API Documentation

Service promiseTracker

  • tracker promiseTracker([options])

    Creates and returns a new promiseTracker.

    Options can be given as an object, with the following allowed values:

    • activationDelay {Number} - Number of milliseconds that an added promise needs to be pending before this tracker is active.
      • Usage example: You have some http calls that sometimes return too quickly for a loading spinner to look good. You only want to show the tracker if a promise is pending for over 500ms. You put {activationDelay: 500} in options.
    • minDuration {Number} - Minimum number of milliseconds that a tracker will stay active.
      • Usage example: You want a loading spinner to always show up for at least 750ms. You put {minDuration: 750} in options.

    Often you want a global promiseTracker (eg to show a loading screen); one easy way is to put the tracker on your $rootScope:

    app.run(function($rootScope, promiseTracker) {
      $rootScope.loadingTracker = promiseTracker();
    });

Instantiated promiseTracker

Example: var myTracker = promiseTracker({ activationDelay: 500, minDuration: 750 });

  • boolean tracker.active()

    Returns whether this tracker is currently active. That is, whether any of the promises added to/created by this tracker are still pending. Note: if the activationDelay has not elapsed yet, this will return false.

  • boolean tracker.tracking()

    Returns whether this tracker is currently tracking a request. That is, whether any of the promises added to/created by this tracker are still pending. This method has no regard for activationDelay.

  • number tracker.trackingCount()

    The count of promises currently being tracked.

  • promise tracker.addPromise(promise)

    Add any arbitrary promise to tracker. tracker.active() will be true until promise is resolved or rejected.

    • promise {object} - Promise to add

    Usage Example:

    var promise = $timeout(doSomethingCool, 1000);
    myTracker.addPromise(promise);
    console.log(myTracker.active()); // => true
    //1000 milliseconds later...
    console.log(myTracker.active()); // => false
  • promise tracker.createPromise()

    Creates and returns a new deferred object that is tracked by our promiseTracker.

    Usage Example:

    var deferred = myTracker.createPromise()
    console.log(myTracker.active()); // => true
    deferred.resolve();
    console.log(myTracker.active()); // => false
  • void tracker.cancel()

    Causes a tracker to immediately become inactive and stop tracking all current promises.

$http Sugar

Requires promise-tracker-http-interceptor.js

  • Any $http call's config parameter can have a tracker field. Examples:
//Add $http promise to tracker with id 'myTracker'
$http('/banana', { tracker: myPromiseTrackerInstance })
//Add $http promise to both 'tracker1' and 'tracker2'
$http.post('/elephant', {some: 'data'}, { tracker: [myFirstTracker, mySecondTracker] })

More Examples

  • Do something whenever the tracker's active state changes
angular.module('app', ['ajoslin.promise-tracker'])

.factory('myTracker', function (promiseTracker) {
  return promiseTracker();
})

.controller('AppCtrl', function ($rootScope, myTracker) {
  $rootScope.$watch(myTracker.active, function (isActive) {
    //doSomething()
  });
});

Development

  • Install karma & grunt with npm install -g karma grunt-cli to build & test
  • Install local dependencies with bower install && npm install
  • Run grunt to lint, test, build the code, and build the docs site
  • Run grunt dev to watch and re-test on changes

New Versions

License

Public Domain Mark angular-promise-tracker by Andy Joslin is free of known copyright restrictions.

More Repositories

1

angular-mobile-nav

An angular navigation service for mobile applications
JavaScript
788
star
2

react-stepper-primitive

React primitives for a "stepper" component.
JavaScript
79
star
3

angular-scrolly

Fake transform-scrolling with angular-friendly utilities
JavaScript
65
star
4

switch-fn

Write a functional switch statement.
JavaScript
42
star
5

react-credit-card-primitives

React primitives for building a credit card form
JavaScript
41
star
6

nanotranslate

Translate with pluralization and variables in under 600b.
JavaScript
36
star
7

react-nanotranslate

React context provider and component for nanotranslate
JavaScript
32
star
8

dot

My dotfiles
Python
24
star
9

stylin

Javascript to CSS: A convenience wrapper around free-style
JavaScript
20
star
10

angular-precommit

JavaScript
19
star
11

parse-google-place

Parse a google place into a normal US address format
JavaScript
13
star
12

react-nanocarousel

JavaScript
11
star
13

just-storage

localStorage with memory fallback that covers the edge cases
JavaScript
9
star
14

queue-that-promise

Push promises to a queue. The queue runs in order. That's all. 500b gzipped.
JavaScript
8
star
15

react-form-lifecycle

Effortless forms, no payload. Render-prop wrapper for npm.im/form-lifecycle
JavaScript
7
star
16

LuaTrig

Create Age of Empires II triggers using Lua scripting language
C++
7
star
17

min-rpc

Minimal rpc server and client using http. Under 3kb in the browser.
JavaScript
6
star
18

app-bridge

A communication bridge between parent and asynchronously loaded child applications
JavaScript
6
star
19

react-animation-primitive

Declarative container for transition/animation event-based component state
JavaScript
5
star
20

daybook

Write a daily journal entry in $EDITOR.
Shell
4
star
21

form-lifecycle

Lifecycle logic for forms: edit, submit, error, success, pending. <1kb.
JavaScript
4
star
22

age-of-python

Create Age of Empires 2 triggers in Python
4
star
23

display-cents

Display cents as a two-digit number for currency. This module is stupidly small.
JavaScript
4
star
24

react-image-primitive

Declaratively fetch image. Use a render prop to get error/pending/loaded state for the image. Set whether the image can be fetched with prop.
JavaScript
4
star
25

sls-promise

Minimal promise-based responses for serverless. Return JSON or full response object.
JavaScript
3
star
26

json-cookie-cutter

Same API as cookie-cutter, plus JSON stringify/parse on set/get.
JavaScript
3
star
27

react-no-update

JavaScript
3
star
28

ng-style

Write javascript styles for Angular 2
JavaScript
3
star
29

picture-in-picture

Picture in picture API in all browsers that support it
JavaScript
3
star
30

observ-falcor

Easily manage Falcor lists / hashes with the observ-family
JavaScript
3
star
31

inline-template

Place your javascript app's templates into your javascript inline!
CoffeeScript
3
star
32

transition-event

CSS Transition handlers for value-event
JavaScript
2
star
33

react-scrolled-in

Detect if an element is scrolled into view. Window or container scrolling. Just a render prop.
JavaScript
2
star
34

busride

Immutable, namespaced event bus
JavaScript
2
star
35

grunt-inline-template

Grunt plugin for http://github.com/ajoslin/inline-template
JavaScript
2
star
36

is-flexbox

Detect support for the modern flexbox spec
JavaScript
2
star
37

react-click-keypress

Spread a click & enter/space key event handler onto an element
JavaScript
2
star
38

or-pipe

Run a sequence of functions until one returns a value
JavaScript
2
star
39

meteor-leaderboard

A small leaderboard written in meteor
CoffeeScript
2
star
40

css-prefixes

Map a subset of common prefixes
JavaScript
2
star
41

dragit.js

A simple jQuery plugin to drag sections of an image around
JavaScript
2
star
42

journal.sh

Effortlessly create a journal entry for today.
Shell
2
star
43

falcor-lazy-model

Call falcor methods before a falcor model is created
JavaScript
2
star
44

forge-weather

Weather app using the trigger.io app framework, Backbone.js, and Zepto.
JavaScript
2
star
45

soft-update-struct

Recursively update an observ-struct, only setting values that changed
JavaScript
1
star
46

simple-browserify-project

JavaScript
1
star
47

eaze-alert

Styled alert component for virtual-dom
JavaScript
1
star
48

array-hash-upsert

Add or update a value in an array/hash pair
JavaScript
1
star
49

app-store-badge

Create a virtual DOM SVG badge for the Google Play Store or App Store
JavaScript
1
star
50

falcor-array

JavaScript
1
star
51

redux-submission

Pending and error states for promises in redux.
JavaScript
1
star
52

queue-that-callback

Run a queue of tasks, with classic callbacks to control task completion
JavaScript
1
star
53

apollo-query-dependson

1
star
54

is-mobile-device

JavaScript
1
star
55

BluetoothSMS-PC

PC Client for Bluetooth SMS
C++
1
star
56

iffy

Ternary in a function, but performant through closure science
JavaScript
1
star
57

css-key

JavaScript
1
star
58

daily-journal

JavaScript
1
star
59

ui-mason

Build server for angular-ui/angular-ui & angular-ui/bootstrap
JavaScript
1
star
60

ng-submission

Keep track of pending/error states in Angular
JavaScript
1
star
61

image-url

JavaScript
1
star
62

react-app-template

My react app template.
JavaScript
1
star
63

angular-burn

Sync an object with Firebase in Angular, and filter the object
JavaScript
1
star
64

observ-varlist

An observable list that can grow negatively or positively
JavaScript
1
star
65

lazybook

Experimental Webpack module for a talk
JavaScript
1
star
66

pascalcase-keys

Convert object keys to PascalCase
JavaScript
1
star
67

oklahoma

Minimal promise-based finite state manager
JavaScript
1
star
68

tcomb-update-path

Update a tcomb object at a path
JavaScript
1
star
69

karma-inline-template-preprocessor

Karma plugin for http://github.com/ajoslin/inline-template
CoffeeScript
1
star
70

assert-my-json-valid

Use is-my-json-valid to validate, throw if error
JavaScript
1
star
71

load-script-once

load a script, but only once
JavaScript
1
star
72

redux-nano

JavaScript
1
star