Showing posts with label $http. Show all posts
Showing posts with label $http. Show all posts
ngimport - Easy to use ES6 imports for $http, $log, and other Angular 1 services

ngimport - Easy to use ES6 imports for $http, $log, and other Angular 1 services

May 18, 2017

ES6 imports for $http, $log, and other Angular 1 services

Example


Note: This example is in TypeScript, but it works equally well in plain JavaScript.

Before:
 import {IHttpService, ILogService, IPromise} from 'angular'  
 angular.factory('Get', function($http: IHttpService, $log: ILogService) {  
  return function(url: string): IPromise<string> {  
   return $http.get(url).then(data => {  
    $log.info('Got data!', data)  
    return data  
   })  
  }  
 })  
 export interface Get {  
  (url: string): IPromise<string>  
 }  
After:
 import {IPromise} from 'angular'  
 import {$http, $log} from 'ngimport'  
 export function Get(url: string): IPromise<string> {  
  return $http.get(url).then(data => {  
   $log.info('Got data!', data)  
   return data  
  })  
 }  


Full Example


Before:
 // Contents of Get.ts:  
 import {IHttpService, ILogService, IPromise} from 'angular'  
 angular.factory('Get', function(  
  $http: IHttpService,  
  $log: ILogService  
 ) {  
  return function(url: string): IPromise<string> {  
   return $http.get(url).then(data => {  
    $log.info('Got data!', data)  
    return data  
   })  
  }  
 })  
 export interface Get {  
  (url: string): IPromise<string>  
 }  
 // Contents of MyComponent.ts:  
 import {Get} from './Get'  
 angular.component('MyComponent', {  
  controller: class MyComponentController {  
   constructor(private Get: Get) {},  
   get() {  
    this.Get('/foo').then(data => ...)  
   }  
  }  
 })  
After:
 // Contents of Get.ts:  
 import {IPromise} from 'angular'  
 import {$http, $log} from 'ngimport'  
 export function Get(url: string): IPromise<string> {  
  return $http.get(url).then(data => {  
   $log.info('Got data!', data)  
   return data  
  })  
 }  
 // Contents of MyComponent.ts:  
 import {Get} from './Get'  
 angular.component('MyComponent', {  
  controller: class MyComponentController {  
   get() {  
    Get('/foo').then(data => ...)  
   }  
  }  
 })  

Why?


Angular 1 DI made sense when there was no JavaScript module standard. But with the advent of CommonJS, and now ES Modules, Angular DI only makes your code less portable.
If you add TypeScript to the mix, you'll often find yourself repeating class interface definitions: you might create a typed service class, but because its dependencies are injected via a closure, you can't export the class directly, and instead need to create a second interface and export it instead! And if you use the class' constructor to inject dependencies, then you can't pass arguments to a new instance of your constructor!
With the ngimport approach, all of these issues are solved.
But the biggest benefit is your code becomes much more portable: you can mix and match Angular 1, Angular 2, or even React components with zero friction. And if you're using TypeScript, you can do all of this in a 100% typesafe way.

Upsides of this approach


  • No more ugly, proprietary DI! Use standard imports
  • No lock in: easy migration path to Angular2, React, etc.
  • Use constructors to pass in arguments, rather than for DI
  • Avoid duplicated TypeScript interface declarations
  • Mock Angular dependencies with $provide in your unit tests, as usual
  • Assert against HTTP requests with $httpBackend in your unit tests, as usual
  • Use it as an adapter to migrate your codebase to imports piece by piece


Using this technique to wrap your own legacy modules


You can easily use the same technique that ngimport uses to expose your own, legacy Angular 1 modules via ES6 imports. Let's say you have the following code:
 // Contents of myModule.js:  
 angular  
  .module('myModule', [])  
  .service('fooService', function($http) {  
   this.foo = function() {  
    return $http.get('/url')  
   }  
  })  
To consume fooService today, you need to DI it; instead, let's expose it and its typings so we can import it:
 // Contents of fooService.ts:  
 import {IPromise, module} from 'angular'  
 export let fooService = undefined  
 interface FooService {  
  foo: () => IPromise<{ data: string }>  
 }  
 module('myModule').run(function ($injector) {  
  fooService = <FooService>$injector.get('fooService')  
 })  
Voila! Now instead of DIing fooService, we can now simply write import {fooService} from './fooService'. We then have the freedom to migrate fooService to TypeScript/ES6 at our own pace.

Limitations


  • Angular builtins ($http, $rootScope) will be undefined until you bootstrap your app. This is due to the way Angular creates injectors. Be careful to either not use these builtins at the top level, or bootstrap the app before you do.
  • If transpiling to CommonJS, be careful to destructure the import rather than importing a default value. Otherwise when the exported reference updates, your consumer will still have a pointer to the old, undefined reference.

License


MIT

Running the tests


 npm test  

Todo


  • Add support for $animate, $animateCss, $aria, $cookies, $provide, $resource, $rootRouter, $route, $routeParams, $routerRootComponent, $sanitize, $swipe, $touch


Note: Special thanks to Boris Cherny

Contact - boris@performancejs.com

Disclaimer: The blog is created to share angular directives information to geek, curious Angular Developer.
Show busy/loading indicators on any element during $http requests (or any promise).

Show busy/loading indicators on any element during $http requests (or any promise).

May 14, 2017

angular-busy


Show busy/loading indicators on any element during $http requests (or any promise). http://cgross.github.io/angular-busy/demo
 Show busy/loading indicators on any $http or $resource request, or on any promise.  

Demo


Live Demo

Getting Started


Install with Bower, npm, yarn, or download the files directly from the dist folder in the repo.
 bower install angular-busy --save  
 npm install @cgross/angular-busy  
Add dist/angular-busy.js and dist/angular-busy.css to your index.html. Add cgBusy as a module dependency for your module.
 angular.module('your_app', ['cgBusy']);  
Add your promise to $scope and reference that in the cg-busy directive:
 function MyCtrl($scope,$http,User) {  
  //using $http  
  $scope.myPromise = $http.get('...');  
  //if you have a User class based on $resource  
  $scope.myPromise = User.$save();  
 }  
 <!-- Use the simple syntax -->  
 <div cg-busy="myPromise"></div>  
 <!-- Use the advanced syntax -->  
 <div cg-busy="{promise:myPromise,message:'Loading Your Data',templateUrl:'mycustomtemplate.html'}"></div>  

Options


The cg-busy directive expects either a promise or a configuration object. In other words. You may do this:
 <div cg-busy="myPromise"></div>  
or this:
 <div cg-busy="{promise:myPromise,message:'Loading',backdrop:false,templateUrl:'myAwesomeTemplate.html',delay:300,minDuration:700}"></div>  
  • promise- Required. The promise (or array of promises) that will cause the busy indicator to show.
  • message- Optional. Defaults to 'Please Wait...'. The message to show in the indicator. This value may be updated while the promise is active. The indicator will reflect the updated values as they're changed.
  • backdrop - Optional. Boolean, default is true. If true a faded backdrop will be shown behind the progress indicator.
  • templateUrl - Optional. If provided, the given template will be shown in place of the default progress indicatory template.
  • delay - Optional. The amount of time to wait until showing the indicator. Defaults to 0. Specified in milliseconds.
  • minDuration - Optional. The amount of time to keep the indicator showing even if the promise was resolved quicker. Defaults to 0. Specified in milliseconds.
  • wrapperClass - Optional. The name(s) of the CSS classes to be applied to the wrapper element of the busy sign/animation. Defaults to cg-busy cg-busy-animation. Typically only useful if you wish to apply different positioning to the animation.
  • Providing Custom Templates


    The angular-busy indicator is a regular Angular template. The templates have access to the scope where cg-busy was declared so you may reference your local scope variables in your custom templates. Additionally, the scope is augmented with a $message field containing the indicator message text.

    Overriding Defaults


    The default values for message, backdrop, templateUrl, delay and minDuration may all be overriden by overriding the $injector value for cgBusyDefaults, like so:
     angular.module('your_app').value('cgBusyDefaults',{  
      message:'Loading Stuff',  
      backdrop: false,  
      templateUrl: 'my_custom_template.html',  
      delay: 300,  
      minDuration: 700,  
      wrapperClass: 'my-class my-class2'  
     });  
    
    Only the values you'd like overriden need to be specified.

    Note: Special thanks to Chris Gross

    Disclaimer: The blog is created to share angular directives information to geek, curious Angular Developer.