Searching for NavigationEnd events specifically in Angular 12?

When using Angular 11, the following code snippet functions correctly:

this.r.events.pipe(
    filter(event => event instanceof NavigationEnd),
    map((event: NavigationEnd) => event.url == ROUTES.APPLICATION))

However, when migrating to Angular 12, it results in the following error:

Argument of type 'MonoTypeOperatorFunction<Event_2>' is not assignable to parameter of type 'OperatorFunction<Event_2, NavigationEnd>'.
Type 'Observable<Event_2>' is not assignable to type 'Observable'.
Type 'Event_2' is not assignable to type 'NavigationEnd'.
Property 'urlAfterRedirects' is missing in type 'RouterEvent' but required in type 'NavigationEnd'.ts(2345)

Do you have any suggestions on how to resolve this issue?

This question provides a solution by adding the following to tsconfig.json:

"paths": {
    "rxjs": [
      "node_modules/rxjs"
    ],
    "rxjs/*": [
      "node_modules/rxjs/*"
    ]
}

However, this did not resolve the issue...

Answer №1

Just did a quick search on Google and found a promising solution. It seems to be a concise version of the type predicate I mentioned earlier. (Source)

filter((event): event is NavigationEnd => event instanceof NavigationEnd))

It would be beneficial to know the initial type of the event parameter in the

.filter(event => event instanceof NavigationEnd)
function

Have you installed a TypeScript plugin in your code editor? Plugins like those in VSCode and Atom can display variable types inline while you code, helping you identify any mismatches.

If

event => event instanceof NavigationEnd
isn't enough to prevent TypeScript errors on the subsequent type assertion (event: NavigationEnd), you might want to consider using a type predicate instead.

Answer №2

Dealing with this issue was incredibly frustrating for me.

After some troubleshooting, I discovered that ensuring the Event was properly imported from @angular/router resolved the issue. Although the linting did not directly point to the lack of Event import as the problem, adding it definitely resolved the issue:

import { Event, NavigationEnd, Router } from '@angular/router'

# NB notice declaration of event as type Event below
filter((event: Event): event is NavigationEnd => event instanceof NavigationEnd))

By addressing this, the functionality now extends to all router events:

router.events.pipe(
  filter((event: Event): event is RouterEvent =>
    event instanceof RouterEvent
  )
)

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

Tips for activating this effect even when the window is resized during page scrolling

There's a code snippet that enables the header to become unfixed when a specific div reaches the top of the screen and then scrolls with the rest of the content. While this solution works perfectly, I encountered a problem where the calculations for ...

What is the proper classification for me to choose?

Apologies for the lack of a suitable title, this question is quite unique. I am interested in creating a function called setItem that will assign a key in an object to a specific value: const setItem = <T, U extends keyof T>(obj: T) => (key: U, ...

Do we need to have the 'input type file' field as

I am currently working on a PHP form that includes mandatory fields for saving the data. For example: <td><input class="text_area required" type="text" name="new field" This form also has Javascript code with file upload functionality, which I ...

Numerous clocks on display

I am trying to display two clocks on my webpage, but for some reason only one clock is showing up. The first clock script is as follows: <script type="text/javascript"> var tmonth=new Array("January","February","March","April","May","June","July"," ...

What methods can I use to minimize the frequency of the blue box appearing around text?

I successfully developed code that enables user interaction with text, triggering the opening of a modal box when clicked. In this modal box, the text turns red upon clicking, indicating activation of a checkbox. However, I notice that every time I intera ...

JavaScript function that shows the name of an individual extracted from a specific file

Hey there, currently I'm diving into a javascript tutorial and exploring ways to display a person's name along with their birthday on this historical day. <script type="text/javascript"> document.write("Today is <br/&g ...

Loop through associative array in PHP using JQuery

I have a PHP associative array and I am using JQuery AJAX to retrieve the result array. My issue arises when passing the result to jQuery and attempting to loop through and extract each Sequence, Percent, and Date. I need to store this extracted data in a ...

Navigating with Angular: Displaying child components on separate pages

When I click on a button in match-controls.component.html, I want my child component (BasicStatControlComponent) to load on a new page. However, the component is rendering directly below the buttons instead. How can I fix this issue? Any help would be appr ...

Leveraging WebWorker in Azure DevOps WebExtension

I am attempting to employ a WebWorker within a WebExtension on an Azure DevOps Server. Data processing for a large repository can be quite resource-intensive, prompting me to utilize a WebWorker for background calculations. However, when I try to instant ...

Create a React component that can be rendered multiple times without duplicating

I have a component that must render a specific item based on the props it receives from its parent component. const Contract = ({ savingsFactors, isContract }) => ( {isContract ? ( <PutField label={label} placeholder={plac ...

`Why is Node.js Express response.download() Not Functioning Properly?`

I have implemented the code below to track active download counts: router.get('/download/:fileName', (req, res) => { let fileName = req.params.fileName; let baseFilePath='/home/filePath'; incrementDownloadCount(fileName) ...

Leveraging the power of jquery-tmpl with the responseText

I am currently working on populating jquery-templates retrieved through an ajax call from a different folder on the server. I attempted to fill the responseTexts using .tmpl({..}) but unfortunately, it didn't work as expected. Here is my approach: va ...

Is the order of state variables important in React components?

Upon executing the code below, an error "Cannot read properties of null (reading 'login')" occurs, triggered by reaching the return statement at the end. This error persists despite the presence of checks for the boolean before the return stateme ...

Is there a way to retrieve the intersection point (Vector3) of the intersectObjects?

I need assistance in finding the point where a ray cast from 'child' intersects with a mesh (child2) using Raycaster: var raycaster = new THREE.Raycaster(); var meshList = []; meshList.push(child2); for (var i = 0; i < child.geometry.vertices ...

Achiever.js - Incorporating incremental progress with half stars instead of whole stars

Hello there! I've been utilizing Rater.js in my current project, and so far it has provided me with satisfactory results. However, I have encountered a particular issue that I am struggling to resolve on my own. It would be greatly appreciated if you ...

Encountering the issue: "Property '...' is not found on the type 'typeof "...."'"

Currently, I am in the process of developing a node js application using typescript. To transpile the code, I am utilizing the gulp transpiler in commonjs mode. One of the files I've written is homeController.ts, which looks like this: let homeContr ...

Make sure to invoke the navigate() function within a React.useEffect() hook, rather than calling it during the initial rendering of

I am new to ReactJS. When the page initially loads, I need to check if the state is null, and if it is, redirect to a different login Page Below is the code for the component: export default function Addblousesalwar() { const navigate = useNavigate(); ...

AngularJS: Recommendations for structuring code to dynamically update the DOM in response to AJAX requests

Within Angular's documentation, there is a straightforward example provided on their website: function PhoneListCtrl($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.order ...

Updating the default color of selected text within a webpage's content

Is there a way to modify the default blue color that appears when content is selected on a webpage? I am wondering how to change this selection color to a custom color of choice. ...

What is the best way to extract data from a JSON object in JavaScript?

let result = JSON.parse(data.d); The current code doesn't seem to be working.. Here is the structure of my JSON object: [{"ItemId":1,"ItemName":"Sizzler"},{"ItemId":2,"ItemName":"Starter"},{"ItemId":3,"ItemName":"Salad"}] Any suggestions on how I ...