Is it possible for the Angular Router to display URLs directly entered into the address bar of the browser

My current router configuration is as follows:

const routes: Routes = [
  {
    path: 'topic/:id',
    component: TopicComponent,
    resolve: { topic: TopicResolverService }
  },  
  {
    path: '',
    pathMatch: 'full',
    component: SummaryCardListComponent
  }
]

If I try to directly access a topic like this:

http://localhost:4200/topic/concepts%2Fdemand%2Flead-time-demand

It ends up redirecting me to http://localhost:4200/.

How can we adjust the router settings to properly render the link provided in the browser?

This is how my topic resolver service implementation looks like:

@Injectable({
    providedIn: 'root'
})
export class TopicResolverService implements Resolve<Topic> {

    constructor( private s: StateService ) { }

    resolve(
        route: ActivatedRouteSnapshot) {
        const id = route.paramMap.get('id')
        return this.s.loadingTopicStore$.pipe(
            switchMap(()=>of(this.s.topicStore.findOneByID(id))
        ))
    }
}

Answer №1

When I apply

decodeURIComponent('concepts%2Fdemand%2Flead-time-demand')
to your URI parameter, originally intended to be an :id, it translates to concepts/demand/lead-time-demand;

This confuses the angular router as it looks for a nested route like:

http://localhost:4200/topic/concepts/demand/lead-time-demand

Since this route does not exist, the application defaults back to the base URL.

REVISION FROM THE AUTHOR OF THE QUESTION

I unintentionally coded an Action that combined various Observable events, including one that signals when the Topic store loading is finished.

This action permitted users to choose a topic category (Concepts, Formulas, Guides, etc.) and upon selection, it would lead to a navigation to '' which is where the selected slice is displayed.

If a URL matching the route was pasted into the browser, triggering a reload of the application, it caused the this.s.loadingTopicStore$ event to activate, resulting in the router navigating to ''.

For those curious, here is the structure of the action:

  /**
   * Note that we're always rendering only
   * `searchedTopics$`, but we also keep track
   * of `selectedTopics$` because we search
   * within this subset when it's selected.
   * 
   * This resets the `topicStore.query`.
   */
  onSelectTopicCategory() {
    merge(
      this.s.loadingTopicStore$,
      this.s.activeTopicCategory$).
      pipe(untilDestroyed(this)).subscribe(() => {
        this.s.selectedTopics$ = combineLatest(
          this.s.all$,
          this.s.guides$,
          this.s.blogs$,
          this.s.concepts$,
          this.s.formulas$,
          this.s.tasks$,
          this.s.activeTopicCategory$,
          this.s.loadingTopicStore$,
          this.onSelectTopicCategoryFunction)
        this.s.searchedTopics$ = this.s.selectedTopics$
        this.s.topicStore.query = ''

        // We have to subscribe to this otherwise
        // The combine latest function will never fire.
        // Since we are only using searchedTopics in the view,
        // we need to manually trigger selectedTopics$.

        this.s.selectedTopics$.
        pipe(untilDestroyed(this)).
        subscribe()
      })
  }

And the function triggered by the merge:


  /**
   * Monitor the active topic category.  
   * 
   * It navigates to '' upon selecting a category
   * to display the selections.
   */
  onSelectTopicCategoryFunction(
    all,
    guides,
    blogs,
    concepts,
    formulas,
    tasks,
    active,
    loading) {
    if (loading == false) {
//      this.router.navigate([''])
      switch (active) {
        case TopicCategories.ALL:
          return all
        case TopicCategories.GUIDES:
          return guides
        case TopicCategories.BLOGS:
          return blogs
        case TopicCategories.CONCEPTS:
          return concepts
        case TopicCategories.FORMULAS:
          return formulas
        case TopicCategories.TASKS:
          return tasks
        default:
          return all
      }
    } else return []
  }

This implementation includes the @fireflysemantics/slice library:

https://www.npmjs.com/package/@fireflysemantics/slice

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

How can we update a boolean value in an Angular service using a set function?

Hey there! I'm currently working on updating a boolean value in my service when a button is clicked within my component. My goal is to trigger the setfunction and toggle the boolean value from true to false, and vice versa when the button is clicked a ...

"Angular SwtAlert2: The Ultimate Multi-Selection Tool

I am trying to integrate the ng-select directive into SweetAlert2, but the code snippet below is not working as expected: const { value: formValues } = await swal.fire({ title: 'Multiple inputs', html: '<ng-select id=" ...

Connecting an Express JS application to the GitHub API: A Step-by-Step Guide

Just recently, I delved into using expressJS for the first time and found myself struggling to connect it to the github API. My aim is to execute commands that can help me retrieve comments and other information from a specific repository. I would greatly ...

"How can I dynamically set the text for a radio button using Reactive Forms? Also, how do I capture the selected radio button value and the question title

If I use a reactive form-array, can I dynamically add 2 questions and 3 or 4 choices? Question 1: How do I set the radio button text dynamically using form-array? Question 2: Now, I'm attempting to retrieve only the selected choice ID corresponding ...

What is the proper way to utilize the uppercase method while ensuring that Turkish characters are not permitted?

Here is the code snippet I am working with: <input type="text" style="text-transform: uppercase" /> When using this code, characters like ü are transformed to Ü. However, I want ü to be transformed to U, so for example, Gülay should become GULA ...

Unattractive destructuring during conditional assignment

When working with object properties, ESLint often suggests using object destructuring. However, this can sometimes result in redundant lines of code. ESLint may not allow something like the following (which might seem like the preferable approach): const ...

Troubleshooting Material-UI: The Mystery of the Missing Dialog

I have been struggling with getting a pop-up dialog to appear when a form is incorrectly filled out. Despite my efforts, the code that should trigger the dialog upon submission does not seem to be working as expected. The function renderError(), responsib ...

The JSON.stringify function encounters difficulties when trying to format an object into

Why does JSON.stringify refuse to format objects and keep everything on a single line? <!DOCTYPE html> <html> <head> <script> var obj = { "a" : "1547645674576457645", "b" : "2790780987908790879087908790879087098", "c" ...

React Error: "SharedArrayBuffer is not defined" Firefox encountered a problem

I am encountering an issue with my React app that was created using 'create-react-app' along with the jsdom NPM package. Strangely, the application is throwing an error upon loading exclusively in Firefox, as it works perfectly fine in Chrome and ...

Testing the subscription feature with unit tests

I am currently testing the reception of an array of people to ensure consistent response types, allowing for detection of any changes in the object from the back-end. Interface Definition: export interface People { peopleDtos: [{ id: number, ...

Tips for optimizing the performance of an Angular 2 website

I am currently developing a website in Angular 2 and have successfully completed one module which I uploaded to the demo path. However, when I tested it using Google Speed Test, it only received a speed score of 37 on desktop and 32 on mobile. Can anyone ...

How come the variable is not being passed to the HTML article within the function?

I'm struggling to pass a variable from a function to an article. Despite successfully displaying the variable in an alert box, I can't seem to get it to show up in the article content. What am I missing? After confirming that "a" contains the co ...

Ways to embed one block of javascript code within another block of javascript code

Can you help me with inserting the following code into a specific part of my JavaScript code? The issue I am facing is that the code contains all JavaScript, and when I directly add it, the gallery crashes. <div id='gallerysharebar'> & ...

Cassandra encountered a TypeError stating that the "value" argument is exceeding the bounds

I keep encountering the error message below. Any thoughts on what might be causing it? TypeError: "value" argument is out of bounds at checkInt (buffer.js:1041:11) at Buffer.writeInt32BE (buffer.js:1244:5) at Encoder.encodeInt (/ ...

JavaScript - Populating Dropdown Menu with Fresh Information

I'm attempting to populate a combobox (input) with data fetched via AJAX. The goal is to display every city associated with a selected state, chosen from another select control (the state control). My Attempt: I've implemented the "change" even ...

How to get the current date and time in JavaScript using a specific timezone

I'm currently working on a project and I was wondering if it's feasible in JavaScript to invoke new Date() for a specific timezone. So when I declare: var test = new Date(); Upon debugging, I notice that the variable test = Date {Fri Nov 07 2 ...

Showing a specific document from an <input> field using AngularJS

I currently have a functional example using standard Javascript, but I am eager to enhance its compatibility with AngularJS. My main objective is to dynamically update the span element with the filename of the file chosen by the user. Below is the code s ...

Getting console data in AngularJS can be achieved by using the console.log()

This log in the console is functioning correctly. Is there a way to retrieve this information for the HTML? ProductController.js $scope.selectedProduct = function(product) { console.log(product.post_title); console.log(product.ID); console.l ...

Ways to display "No records" message when the filter in the material table in Angular returns no results

How can I implement a "No Records Message" for when the current table is displaying empty data? Check out this link for examples of material tables in AngularJS: https://material.angular.io/components/table/examples ...

Is there a streamlined approach to signal a successful callback to $q.all without the need to define a $q.defer() variable?

Within my application, I have a mixture of synchronous and asynchronous methods. Here is an example of code from one of the controllers: $q.all([ asyncMethod1(), syncMethod1() ]) .then(function (results) { Even though I don't actually need t ...