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?
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"?
EDIT: For a Angular 2+ Solution look into my answer below. Its a service for intercepting tags.
What Are Http Interceptors And How to Use Them In Angular? Use cases where we can make use of Interceptors in Angular. We have faced multiple scenarios where we might want to globally capture or change every request or response, like append a user’s token or handle errors from the response and we can achieve this using Http Interceptor.
This is only possible because Angular has an intelligent way of processing the requests. According to the Angular documentation: Angular applies interceptors in the order that you provide them. For example, consider a situation in which you want to handle the authentication of your HTTP requests and log them before sending them to a server.
Interceptors allow us to intercept incoming or outgoing HTTP requests using the HttpClient. They can handle both HttpRequest as well as HttpResponse. By intercepting the Http request, we can modify or change the value of the request, and by intercepting the response, we can do some predefined actions on a particular status code or message.
If an interceptor could modify the original request object, the re-tried operation would start from the modified request rather than the original. Immutability ensures that interceptors see the same request for each try.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With