Accessing objects using string literals is restricted! I am encountering an issue while attempting to access the route parameter 'id' via a dynamic ID

Let's take a look at my custom [app-routing.modulse.ts] module:

const appRoutes: Routes = [
    { path: '', redirectTo: '/recipes', pathMatch: 'full' },
    { path: 'recipes', component: RecipesComponent, children: [
        { path: '', component: RecipeStartComponent },
        { path: ':id', component: RecipeDetailComponent },
    ] },
    { path: 'shopping-list', component: ShoppingListComponent },
];

@NgModule({
    imports: [RouterModule.forRoot(appRoutes)],
    exports: [RouterModule]
})

export class AppRoutingModule {

}

This snippet showcases the childComponent RecipeDetailsComponent which is causing an error when attempting to access the route parameter 'id':

import { Component, OnInit, Input } from '@angular/core';
import { Recipe } from '../recipe.model';
import { RecipeService } from '../recipe.service';
import { ActivatedRoute, Params, Router } from '@angular/router';

@Component({
    selector: 'app-recipe-detail',
    templateUrl: './recipe-details.component.html',
    styleUrls: ['./recipe-details.component.css']
})

export class RecipeDetailComponent implements OnInit {
    recipe: Recipe;
    id: number;
    constructor(private recipeService: RecipeService,
        private route: ActivatedRoute,
        private router: Router) {
    }

    ngOnInit() {
        this.route.params.subscribe((params: Params) => {
            // The error occurs here
            this.id = +params['id'];
            this.recipe = this.recipeService.getRecipe(this.id);
        });
    }
}

Encountering the error message "object access via string literals is disallowed" is a result of trying to retrieve the dynamic route parameter 'id'.

Answer №1

Can you please give this a try?

route.params.subscribe((params: {id: string}) => {
  this.id = +params.id;
})

**I'm making adjustments based on the feedback

Simply update the appRoutes to include:

const appRoutes: Routes = [
 { path: 'recipes', component: RecipesComponent, children: [
 { path: ':id', component: RecipeDetailComponent },
 { path: '', component: RecipeStartComponent },
  ] }, //add any additional routes here......

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

Next.js 13 app directory experiences 404 Not Found error due to dynamic routing issues

I recently built a straightforward to-do app using Next.js 13 paired with TypeScript. The process involved creating an array of objects, each comprising an id string and a name string. Subsequently, I iterated through the list and showcased the names withi ...

The email address [email protected] is in need of a jasmine peer version equal to or greater than 3, yet there are no such

After upgrading jasmine-core to version 3.1.0, I decided to also update karma-jasmine-html-reporter to the latest version 1.1.0 npm i --no-optional This command resulted in: npm WARN [email protected] requires a peer of jasmine@>=3 but none ...

Resetting the selected value in an Angular2 select element after the user makes a change

I have a dropdown menu which the user can select an option from. Initially it has a default value and when the user makes a new selection, I need to ask for confirmation by showing a message "are you sure?". If the answer is NO, then I should revert back t ...

Angular is unable to access a service method through an observable subscription

Currently, I have a code for my service like this: cars() { return 'something here'; } Next, in order to retrieve the data using an observable from the component, I am attempting the following: getcars() { this.dataService.cars().subsc ...

What is the technique for highlighting the exact data point on the XY am4chart when it is clicked?

I have been searching high and low for a solution to my problem but haven't had any luck. I am working with a traditional XY am4chart that has hundreds of data points in the line series. What I want is for the chart to display a vertical line (or some ...

Revolutionizing the way data is updated: Angular 2 and Node JS collaborate

In my Angular 2 application, I have incorporated a dynamic navbar that displays the count of unread messages for each user. Interestingly, when a person clicks on a specific message, it is correctly marked as read in the database. However, an issue arises ...

Are you on the lookout for an Angular2 visual form editor or a robust form engine that allows you to effortlessly create forms using a GUI, generator, or centralized configuration

In our development team, we are currently diving into several Angular2< projects. While my colleagues are comfortable coding large forms directly with Typescript and HTML in our Angular 2< projects, I am not completely satisfied with this method. We ...

Angular uploading image via WCF service call

I have been facing an issue while trying to upload an image from my Angular frontend through wcf. The upload process is successful and I receive a success message, however, the saved image is not viewable in any image viewer or program. The code snippet u ...

Loading data from a remote source in an Angular 6 material table: A step-by-step guide

I'm currently puzzled by the usage of the material table schematic and am struggling to find a solution. It appears that the key aspect lies within the connect() method present in the datasource.ts file. Simply put, this.data is merely an array. / ...

Prisma: Utilizing the include option will retrieve exclusively the subobject fields

I created a function to filter the table building and optionally pass a Prisma.BuildingInclude object to return subobjects. async describeEntity(filter: Filter, include?: Prisma.BuildingInclude): Promise<CCResponse> { try { const entity = await ...

Pair two values from the interface

I need to extract and combine two values from an Interface: export interface CurrenciesList { currency: string; country: string; } The initial mapping looks like this: this.optionValues["currency"] = value.map(i => ({ id: i.currency, name: i.curr ...

Encountering Error 203 while trying to establish a connection between Angular and Django Rest Api

I'm currently working on a project that involves creating a contacts system, but I've been encountering errors when trying to list them. Interestingly, I can successfully perform CRUD operations using Postman with the API. One of the messages I ...

Inquiring about the application of spread argument in TypeScript

Here is some code I'm working on: import _ from 'lodash'; function test(num1: number, num2: number) { console.log(num1, num2); } test(..._.take(_.shuffle([0, 1, 2]), 2)); I encountered a TS2556 error while using the TS playground and ...

Chart of commitments and potential outcomes

I am in the early stages of learning about promises and I am struggling to understand how to write code correctly. Here is an overview of what the program should do: Retrieve a list of item types (obtained through a promise) Loop through each item type to ...

Issue encountered: Angular material table is not providing support for truncating cell text with ellipsis

Greetings! I am currently utilizing Angular Material table in my grid. While mat-table automatically adjusts the cell height to accommodate long text, I prefer to maintain a consistent height and display ellipsis instead. Does anyone have any suggestions ...

What could be causing the "buffer is not a function" error to occur?

As a beginner with observables, I'm currently working on creating an observable clickstream to avoid capturing the 2 click events that happen during a double-click. However, I keep encountering this error message:- Error: Unhandled Promise rejection ...

Tips for maintaining the original data type while passing arguments to subsequent functions?

Is there a way to preserve generic type information when using typeof with functions or classes? For instance, in the code snippet below, variables exampleNumber and exampleString are of type Example<unknown>. How can I make them have types Example& ...

Problems encountered with Bootstrap navbar-nav while utilizing ngFor

Greetings, I am currently utilizing bootstrap v4.0.0 in my project. I have noticed that when displaying menus using navbar-nav and implementing ngFor, the bound property seems to be called continuously - is this the intended behavior? Below is a snippet o ...

Unable to call a component's method from a different component in Angular 7

How can I call the toggleSidebar() method of the SidebarComponent from the HeaderComponent using the callToggleSidebarOnToggleSidebarBtn() method? I am encountering an error that I cannot comprehend. What is the correct way to use a method of one component ...

Deduce the generic types of conditional return based on object property

My goal is to determine the generic type of Model for each property. Currently, everything is displaying as unknown[] instead of the desired types outlined in the comments below. playground class Model<T> { x?: T } type ArgumentType<T> = T ...