Invoke a TypeScript function when the URL is modified

In my TypeScript Angular controller, I am looking to create a method that triggers every time the URL changes - even if it's just a small part of the URL like a number. I have already implemented the method I want to trigger and it is located within the constructor of the controller. My question is how do I determine when to trigger this method and where should I call it? Should I initialize it inside the constructor?

Here is an excerpt of my controller's code:

private returnedClass: Class;
    static $inject: Array<string> = ['$scope', 'common', 'repository.class'];
    constructor(public scope: any, public common: app.core.Common, public myService: app.data.IRepositoryClass) {           
    }           
    getFromDB(): void{
        if (location.href.indexOf("classAdd") !== -1 && typeof this.common.itemId !== 'undefined' && this.common.itemId != null)
        {
          this.myService.getClassById(this.common.itemId).then((returnedItem: Class) => {
              this.returnedClass = returnedItem;
              console.log(this.returnedClass);
            });
        }
    }
}
angular
    .module('app.layout')
    .controller('HeaderNavigationController', HeaderNavigationController);

I should note that this controller is executed once when the entire HTML DOM is loaded (index.html). Do I need to implement a watcher or some other mechanism for this? How can I achieve that?

Thank you in advance

Answer №1

If you are using angular uiRouter, make sure to listen for the $stateChangeSuccess event:

constructor(private $scope: any, private commonService: app.core.Common, private myDataService: app.data.IRepositoryClass) {    

    $scope.$on('$stateChangeSuccess', () => this.fetchDataFromDatabase());
} 

Quick Tip: It's recommended practice to designate your dependencies as private instead of public.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The term 'detailed' is not a valid property for the type 'Console'

I enjoy customizing my console logs. //-- Personalized console logging functions console.detailed = function(payload) { return console.log(util.inspect(payload, { showHidden: false, depth: null })) } console.notice = function(payload) { return co ...

Transforming an array of strings into a Name/Value object using JavaScript

Recently, I encountered a Web Service that sends an array of strings to the client. My goal is to transform this array into an object where each string has a name for future reference. Let's start with: var result = ["test", "hello", "goodbye"]; An ...

Implement a dynamic table in real-time with jQuery AJAX by fetching data from JSON or HTML files

Hey @SOF, I'm trying to add an auto-update feature to my school grades webpage using jquery and ajax to refresh the data when new information is available. I also want to create a "single view" for classes. The challenge I'm facing is getting t ...

The clarity of JS invariants may be questionable

Why does the invariant function have these parameters: function(condition, format, a, b, c, d, e, f) { instead of: function invariant(condition : any, format?: string, ...args : Array < any >) { Could someone please explain this to me, as it does ...

Tips for patiently anticipating the resolution of a new promise

Searching for a way to ensure that a promise waits until a broadcast is fired, I came across some enlightening posts on this platform and decided to implement the technique detailed below. However, it appears that the broadcastPromise does not actually wai ...

Problem with assigning onclick to a function

I've been working on adding an onclick function to my code, using the following line: newbutton.onclick = whoWon(this.id) Here's some other relevant code: var winner; function whoWon(name){ winner = name; } The issue I'm facing is tha ...

ng-repeat to display items based on dropdown choice or user's search input

Utilizing $http to retrieve JSON data for display in a table. I have successfully implemented a search functionality where users can search the JSON data from an input field. Additionally, I now want to include a feature that allows users to filter the JSO ...

Invoke the function when you finish typing in React.js

After I finish typing, I want to execute some code. I attempted to use the following script but it didn't work as expected const stopTypingHandler=(e)=>{ let time; clearTimeout(time); time = setTimeout(() => { console.log("click& ...

Tips for persisting form values even after refreshing the page - a guide to setting form values that stay in place

When I submit a long form, an external JavaScript validation is triggered to check the input field validity. If all fields pass validation, a jQuery modal appears prompting the user to either register or log in. If the user chooses to register and complet ...

The Jquery Countdown plugin fails to initialize

Currently struggling with getting the jquery Countdown plugin to work for a 12-day countdown. Despite all efforts, the countdown does not seem to start and I am at a loss on how to troubleshoot this issue. After searching online extensively, I have yet to ...

Leveraging a standalone Vue project as a node package within another project

I'm facing a challenge in my projects due to architectural changes and am in need of some guidance to move forward. Here is the issue at hand. Situation Originally, I began with a single Vue application that included various components such as queryi ...

The reason behind angular expressions resulting in empty strings when evaluated within an attribute

What could be causing angular expressions within an element's attribute to evaluate as empty strings when there are multiple expressions present? In a specific scenario, I have an attribute with identical expressions that output scope variables. Howev ...

Modifying the CSS style of an element on PageA by clicking a button on PageB

For my app, I am incorporating tabs. I want to implement a user button that, when clicked on tab-detail.html, will update the CSS of an element located on its parent tab page, tab.html. .controller('TabCtrl', function($scope,Tabs) { $scope.t ...

When a 404 error is thrown in the route handlers of a Next.js app, it fails to display the corresponding 404 page

I am encountering an issue with my route handler in Next.js: export async function GET(_: Request, { params: { statusId } }: Params) { const tweetResponse = await queryClient< Tweet & Pick<User, "name" | "userImage" | &q ...

Storing a blank field in a Kendo grid

Is there a way to clear the content of a cell and save it as an empty field? I attempted to specify my field in the parameter update map using the following code: ((data.Value) ? '","Value": "' + data.Value : "") + and in the schema like this: ...

Switch the orientation of a live table moving horizontally to vertically and vice versa

config.previewData = [ { Products:27989, Total Customers:294, Metrics:"MVC", Toner Products:5928, INK Products:22061 }, { Products:56511, Total Customers:376, Metrics:"SMB", ...

What potential factors could lead to an MUI Snackbar failing to produce the accurate class names?

I am facing an issue with displaying notifications on my Gatsby blog whenever the service worker updates. I am using a MUI Snackbar toast for this purpose. However, sometimes the styling of the toast is not applied correctly and it ends up looking like thi ...

In Javascript, update the text that was copied and pasted

I have content in a div that is editable by the user, and they can copy certain parts of it and paste them back into the same div. However, there are styles associated with the copied text, so I only want to extract the text itself from the copied content. ...

What is the process for displaying HTML page code received from an AJAX response?

My current project involves implementing JavaScript authentication, and I have a specific requirement where I need to open an HTML file once the user successfully logs in. The process involves sending an AJAX request with the user's username and passw ...

What is the best way to configure dependencies for a production deployment when utilizing Babel within the build script?

From what I understand, Babel is typically used for compiling code, which is why it usually resides in devDependencies. However, if I incorporate the Babel command into my build script and want to run npm install --only=prod before running npm run build d ...