Error message: Unable to retrieve parameter value from Angular2 ActivatedRoute

I am attempting to showcase the value of the activated route parameter on the screen, but I am facing difficulties.

In the initial component, my code looks like this:

<ul *ngFor="let cate of categories;">
  <li (click)="onviewChecklists(cate.id)">
     <a> {{i+1}} {{cate.category}} </a>
  </li>

</ul>

  onviewChecklists(category:string){
     this._router.navigate(["tsafety/checklist-management/categories/items",
       {category:category}])
 }

Now, in the second component where I am navigating to, my code is as follows:

category:any;

constructor(
private _router:Router,private activeRoute:ActivatedRoute
 ) {

 }

ngOnInit() {

   this.category = this.activeRoute.snapshot.params['category'];
   console.log(this.category);  //this works
} 
//On this component HTML {{category}} only returns the first param

In the HTML file of the second component, when I use {{category}}, it only displays the value of the first routing. For example:

navigate 1 param is checklist display is checklist
navigate 2 param is newcheck display is checklist

I have checked that the console.log() prints the correct value, but {{category}} only shows the first value.

In the second component, I have also tried the following:

ngOnInit() {
 this.onGetItems(+this.activeRoute.snapshot.params['category']);

 }

 onGetItems(category){
    return this._checklistitemsService.getAllItems(category)
    .subscribe(
       res=>{
         this.checklistitems = res
    }
  )

The onGetItems method is only called once.

Answer №1

Whenever passing a route parameter and making a service call using that parameter, it is recommended to subscribe to the activated route using an Observable<params> in the constructor as shown below:

category: number = 0;
constructor(private route:ActivatedRoute, 
            private checklistitemsService: CheckListItemsService) {

    this.sub = this.route.params.subscribe(params => {

            this.category = + params['category'];
              ......

    });
}

Make sure to place your service call inside the ngOnInit() method:

ngOnInit(){
      this._checklistitemsService.getAllItems(category)
          .subscribe(res => {
                          this.checklistitems = res
           }
}

Common Mistake:

If you try to retrieve the route params in ngOnInit, the components will load before the route value is obtained, resulting in a delay and leaving this.checklistitems without a value.

Solution:

To avoid this issue, ensure to retrieve the route parameters in the constructor so that ngOnInit waits for the parameter before executing, allowing the service call to populate this.checklistitems. This approach ensures correct loading of your component.

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

Angular2 calendar and time selector

Having trouble setting up a date and time picker for my angular2 app. Can anyone provide assistance with this? I've experimented with the following methods: Ng2-datetime: I added it to the main app.module file: import { NKDatetimeModule } from &ap ...

In Typescript, null values are allowed even when the type is set to be non-nullable

Can someone explain why the code below allows for null in typescript, even though number is specified as the type: TS playground // Not sure why null is accepted here when I've specified number as the type const foo = (): number => 1 || null ...

Utilize the object's ID to filter and display data based on specified criteria

I retrieved an array of objects from a database and am seeking to narrow down the results based on specific criteria. For instance, I want to display results only if a user's id matches the page's correct id. TS - async getResultsForId() { ...

Tips for stopping the navigator from adding content to an HTML input in an Angular application

I am facing an issue with two input fields in my Angular project. These fields are supposed to take values automatically from the browser, and I have tried using the HTML autocomplete option without success. Here is a snippet of my HTML code: <div clas ...

Update gulp configuration to integrate TypeScript into the build process

In the process of updating the build system for my Angular 1.5.8 application to support Typescript development, I encountered some challenges. After a complex experience with Grunt, I simplified the build process to only use Gulp and Browserify to generat ...

Dynamic content within an Angular Swiper

Greetings, Experts! I am a newcomer to angular and have successfully created 3 components: Swiper YouTube frame Map display Currently, I am facing a challenge where I need to utilize the swiper component multiple times on the homepage. The first instanc ...

Guide on integrating a dynamic element within another element in Angular

Imagine a scenario where we have the following html structure <div [innerHTML]="contentFromAPI | safeHTML"></div> The content retrieved from the api contains multiple HTML elements, resulting in a structure like this: <div> &l ...

Adding jQuery and other libraries to Typescript for optimal functionality

After spending days researching and struggling, I am reaching out here for clarification on the process of importing a library in Typescript. I used to just add the script tag and everything would work fine. Now that I am working on building a MEAN-Stack ...

"Encountering a TypeScript error when using React Query's useInfiniteQuery

I am currently utilizing the pokeApi in combination with axios to retrieve data import axios from 'axios' export const fetchPokemonData = async ({ pageParam = "https://pokeapi.co/api/v2/pokemon?offset=0&limit=20" }) => { try ...

How can I enable email and password login in @auth0/auth0-angular?

Auth0 SDK for Angular Single Page Applications - the documentation outlines two methods for logging in: loginWithPopup loginWithRedirect Is there a possibility to add another option for logging in with just an email and password? ...

Accessing collection values from referenced document IDs in Firestore---I have provided a unique version of the text

I have two fire store collections with the following reference images: https://i.sstatic.net/QVJkZ.pnghttps://i.sstatic.net/0QFRi.png. I am trying to retrieve the firstName and title from these collections. The signup_id is referenced from the document id ...

React Type Mutation response feedback is a valuable tool for receiving input

I am facing an issue with passing the mutation success response in my code. I have a file named change-email.tsx which calls a component file updateEmail.tsx containing a mutation function. The submit function is working fine, but I cannot figure out how t ...

What is the issue with assigning type {intrinsicattributes & true} or type {intrinsicattributes & false} in a React and TypeScript environment?

I am facing an issue with the following code snippet: function Parent() { const count1 = 2; const count2 = 4; const isCount = count1 < 0 || count2 < 0; //setting isCount here return show ? ( <Dialog> ...

Can data be filtered based on type definitions using Runtime APIs and TypeDefs?

My theory: Is it feasible to generate a guard from TypeDefs that will be present at runtime? I recall hearing that this is achievable with TS4+. Essentially, two issues; one potentially resolvable: If your API (which you can't control) provides no ...

How can I prevent the installation of my Ionic 2 application on devices that have been rooted or jailbroken?

I am currently working on a project involving an Ionic 2 and Angular 2 application. I need to implement a feature that checks whether the device is rooted (in the case of Android) or jailbroken (in the case of iOS). I have experimented with various packag ...

Employing ngModel in an option dropdown

I am having trouble passing an attribute from an API call to a submit function. I suspect it might have something to do with either the option select or how the input is being formatted. Encountering the error Error: No value accessor for form control wit ...

How to retrieve the value of a nested checkbox in Angular using dynamic methods

I successfully developed dynamic nested checkboxes in Angular and now I am looking to retrieve the values of the selected checkboxes. However, I encountered an issue with the JSON structure needed to implement this functionality. https://i.stack.imgur.com ...

Create TypeScript declaration files dynamically within the application's memory

Is there a way to programmatically generate declaration files using TypeScript? I know we can use tsc --declaration --emitDeclarationOnly --outFile index.d.ts, but I'm not sure how to do it in code. For example: import ts from 'typescript' c ...

What is the process for showcasing a local notification within my application?

Here is the code snippet I am working with: import { LocalNotifications } from '@ionic-native/local-notifications'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scs ...

Angular Material card layout design

I am looking to create a unique gallery layout for my images using polaroid card-based system with multiple rows and columns. The issue I am encountering is with the mat-card attribute stretching to match the size of portrait images, causing distortion in ...