Freddy Ewald Personal Website

Posts


  • Angular2 - Loading indicator for Http service

    I wanted to notifiy the user, whenever I am doing an AJAX request in Angular2. To achieve this in an existing project, the goal was, to edit as little files as possible. The solution to this problem is very straightforward: The class Http needs to be extended which allows own code to be used.

    First, I needed to create the EventHttpService with the following code:

    import { Http } from '@angular/http';
    export class EventHttpService extends Http{}
    

    So far this class does nothing, it just extends the Http class, providing the same functionality. Therefore I needed to override all the methods which should perform a different action. Below is an example for the get method, with all the required imports. Of course, the whole class needs to be decorated with Injectable() so that we can inject it via Dependency Injection.

    import { Injectable } from '@angular/core';
    import { Http, RequestOptions, RequestOptionsArgs, Response, ConnectionBackend } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    
    @Injectable()
    export class EventHttpService extends Http {
    	public get(url: string, options?: RequestOptionsArgs) : Observable<Response> {
    			// Own code before the request is performed
    			var response = super.get(url, options);
    			response.subscribe(null, error => {
    				// Own code on error
    			}, () => {
    				// Own code on success
    			});
    			return response;
    	}
    }
    

    The comments in the source code above mark the points where the developer can implement own code. I used it, to increment and decrement a counter. When the counter starts from 0, an injected loading bar is shown and when the counter finally reaches 0, the loading bar is hidden.

    So far, the class does nothing, since we are not using it. The right place to use it, is app.module.ts:

    @NgModule({
      imports:      [],
      declarations: [],
      providers: [
        HTTP_PROVIDERS,
        provide(Http, {
          useFactory: (xhrBackend: XHRBackend, requestOptions: Request) => new EventHttpService(xhrBackend, requestOptions),
          deps: [XHRBackend, RequestOptions]})
        ],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }
    

    With this example, whenever Http.get is used, the EventHttpService is used automatically, executing my custom code. If you want to inject other services into Http, this is also straightforward, just add these to the constructor of the EventHttpService so that it looks as follows. In my case, I am using the awesome ng2-slim-loading-bar to show a loading bar, when the first AJAX request is performed.

    public constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions, private loadingBar: SlimLoadingBarService) {
    	super(_backend, _defaultOptions);
    }
    

    Below is the complete code of the event-http.service.ts:

    import { Injectable } from '@angular/core';
    import { Http, RequestOptions, RequestOptionsArgs, Response, ConnectionBackend } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    import { SlimLoadingBarService } from 'ng2-slim-loading-bar';
    
    @Injectable()
    export class EventHttpService extends Http {
    	private currentRequests: number = 0;
    
    	public constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions, private loadingBar: SlimLoadingBarService) {
    		super(_backend, _defaultOptions);
    	}
    
    	public get(url: string, options?: RequestOptionsArgs) : Observable<Response> {
    		this.incrementRequestCount();
    		var response = super.get(url, options);
    		response.subscribe(null, error => {
    			this.decrementRequestCount();
    		}, () => {
    			this.decrementRequestCount();
    		});
    		return response;
    	}
    
    	private decrementRequestCount() {
    		if (--this.currentRequests == 0) {
    			this.loadingBar.complete();
    		}
    	}
    
    	private incrementRequestCount() {
    		if (this.currentRequests++ == 0) {
    			this.loadingBar.start();
    		}
    	}
    }
    

  • VIM cheatsheet

    A cheatsheet for vom can be found here. I find this quite useful to begin with this powerful editor.

    The most important keys, if you just want to edit a file are:

    • i insert
    • esc exit insert mode
    • j move cursor down
    • k move cursor up
    • h move cursor left
    • l move cursor right
    • :w write (append the filename)
    • :q quit
    • :q! quit and do not save changes

  • Big O notation for many datatypes

    An interesting site which shows the Big O notation for all many commonly used datatypes is the Big O Cheatsheet.

  • Show open ports on the linux shell

    If you want to show all the currently open ports on linux, just use the following command:

    netstat -lntu
    

    This gives you the following output:

    Active Internet connections (only servers)
    Proto Recv-Q Send-Q Local Address           Foreign Address         State
    tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
    tcp        0      0 0.0.0.0:3128            0.0.0.0:*               LISTEN
    tcp6       0      0 :::22                   :::*                    LISTEN
    udp        0      0 0.0.0.0:39790           0.0.0.0:*
    udp        0      0 0.0.0.0:68              0.0.0.0:*
    udp        0      0 0.0.0.0:41121           0.0.0.0:*
    udp6       0      0 :::57063                :::*
    udp6       0      0 :::42147                :::*
    

    Found here

  • Using git efficiently on the console

    I was looking for ways to visualize the progress of a project and also I wanted to do this with on-board tools. After a quick search I found the following command.

    git log --graph --decorate --oneline
    

    This gives a nice and colorful overview when what branch was touched and how it was merged. To display the results in a nicer way, a alias in the ~/.giconfig helps:

    [alias]
    lg = !"git lg1"
    lg1 = !"git lg1-specific --all"
    lg2 = !"git lg2-specific --all"
    lg3 = !"git lg3-specific --all"
    
    lg1-specific = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)'
    lg2-specific = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n''          %C(white)%s%C(reset) %C(dim white)- %an%C(reset)'
    lg3-specific = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%
    

    The last speed trick is, to set an alias in the ~/.bashrc. This saves 2/3 of the letters.

    alias g='git'
    

Page: 11 of 14