Search code examples
angularhttprequesthrefinterceptor

intercept outgoing links Angular 4


so I write this small app where I show some information fetched from Wikipedia. There are also links inside of this fetched HTML.

So what I want to do:

Every time the user clicks on a link I want to intercept this and do custom behavior instead of the default browser redirect.

The build in Angular httpinterceptor is not working here. How do I get this effect?

CODE:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {

  constructor() {

  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { //HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
    console.assert(true, 'Intercepting Link request!' + request.url);
    return next.handle(request);
  }
}

Do I misunderstand something perhaps?

EDIT: seems like I misunderstood how the href and http requests work. Still I want to do custom behaviour on every link clicked on my application. Is there no possible way to intercept those "events"?


Solution

  • Okay after searching a little longer I found a "not angular" solution: Override default behaviour for link ('a') objects in Javascript

    And so I created a service out of this and injected it in my App Root component.

    import { Injectable } from '@angular/core';
    
    @Injectable() export class HrefInterceptorService {
    
        constructor() {
            document.onclick = this.interceptHref;
        }
    
        interceptHref(_event) {
            const tEvent = _event || window.event;
    
            const element = tEvent.target || tEvent.srcElement;
    
            if (element.tagName === 'A') {
    
                console.log("intercept!");
    
                return false; // prevent default action and stop event propagation
            }
        } }
    

    Its a little hacky but relatively flexible.