The ActivatedRoute snapshot does not function properly when used in the TypeScript class constructor

Currently, I am encountering a challenge with TypeScript and Angular 2. The structure of my TS class is as follows:

'import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-blogdetail',
  templateUrl: './blogdetail.component.html',
  styleUrls: ['./blogdetail.component.css']
})
export class BlogdetailComponent implements OnInit {

   blogId:any;
   title:any;

    constructor(private _activatedRoute:ActivatedRoute) {
    // Does not work
     // this.blogId = this._activatedRoute.snapshot.params['id'];
    //this.title= `This is blog detail for blogID:${this.blogId}`;

   }

  ngOnInit() {
      this.blogId = this._activatedRoute.snapshot.params['id'];
    this.title= `This is blog detail for blogID:${this.blogId}`;
  }

}'

I am trying to retrieve the route parameter in the ngOnit event. When I initially attempt to obtain the parameter in the TS class constructor, the value of the blogId variable is returned as undefined. Upon analyzing the sequence of events, it seems to resemble the flow illustrated in the image below: ![flow]https://i.stack.imgur.com/41fpe.png

Is it mandatory to always retrieve the activatedRoute snapshot values in ngOnIt?

Answer №1

That's correct. The issue arises when your component is initialized for your view, as only a new instance is created at that moment without activating the route, resulting in missing route parameters. Conversely, utilizing it in OnInit ensures that the route is activated and you are able to access the params. However, it is advisable to subscribe to the route params within your OnInit method to properly retrieve the params such as:

ngOnInit(){
    this.routeParamsSub = this.route.params.subscribe(routeParams => {
        this.blogId = routeParams['id']; 

       // implement additional logic here
    });
}

A similar approach can be found in this resource.

Answer №2

During the creation of an object in angular, the params are not available.

Therefore, you should use it either within the ngOnInit method to assign it to a variable.

If you insist on having this code inside the constructor, you can use observables like so:

@Component({...})
class MyComponent {
  constructor(route: ActivatedRoute) {
    const id: Observable<string> = route.params.map(p => p.id);
    const url: Observable<string> = route.url.map(segments => segments.join(''));
    // route.data includes both `data` and `resolve`
    const user = route.data.map(d => d.user);
  }
}

However, using ActivatedRoute in the constructor is considered a bad practice in my opinion.

For more information, you can refer to the ActivatedRoute-interface documentation

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 and the Use of Environment Variables

I am working on an angular 2/4 app with a node server.js to serve it. I need to access an environment variable for switching between backend endpoints (using localhost for dev and another endpoint for prod). Both the frontend and backend apps are destined ...

Facing a Bad Request error while trying to submit a Django Rest Framework Post request that appears to be valid, but is requiring a

Currently, I am in the process of creating a new instance of the SearchNeighborhood object and establishing a connection with an already existing SearchCity object through a POST request. The models I have set up are as follows: class SearchCity(models.M ...

arrange items based on their category into arrays

I have a JSON file that needs to be arranged based on three specific fields. Here is an example snippet of the JSON data: { "Racename": "10KM", "Category": 34, "Gender": "Male", "Work": "Google", "FullName": "Dave Happner", "Rank": 1, "Poni ...

Accurate TS declaration for combining fields into one mapping

I have a data structure called AccountDefinition which is structured like this: something: { type: 'client', parameters: { foo: 3 } }, other: { type: 'user', parameters: { bar: 3 } }, ... The TypeScript declaration ...

Extracting data from HTML elements using ngModel within Typescript

I have an issue with a possible duplicate question. I currently have an input box where the value is being set using ngModel. Now I need to fetch that value and store it in typescript. Can anyone assist me on how to achieve this? Below is the HTML code: ...

Passing a custom data type from a parent component to a child component in React

I'm currently working on developing a unique abstract table component that utilizes the MatTable component. This abstract table will serve as a child element, and my goal is to pass a custom interface (which functions like a type) from the parent to t ...

The Angular directive HostBinding is often used in conjunction with the

Is it possible to add a routerLink to the Host Element within an Angular Component? I attempted the following: @HostBinding('routerLink') routerLink = '/my-route' However, clicking on the component does not navigate to the specified ro ...

Angular 2 chart showing horizontal stacking of databars

I am in search of a chart that visually represents different percentages. The purple bar should represent around 40%, the darkest blue approximately 10%, and the green about 8% of the total. After some research, I have come across this as a similar option, ...

Lint found an issue: The variable 'post' has been defined but is not being utilized in the code

Within my codebase, I have included the following import: import { post } from '@loopback/rest' This is how I am utilizing it in my project: export class MyClass { @post('/example/test', {}) } Unfortunately, a lint error has been de ...

Using Angular, you can incorporate a dynamic href inside interpolation by using

Looking for a way to include a redirecting link within the response of string interpolation. I am incorporating the API response value into the interpolation binding. For instance, if my response is, "This site is not working. please contact google f ...

In Typescript, the module source is imported rather than the compilation output

I created a custom module for personal use and decided to host it on a private GitHub repository. Within the module, I have included a postinstall script that runs: tsc -d -p .. Currently, the generated .js and .d.ts files are located alongside the source ...

How can I use Angular 4 typescript to deactivate a button based on the value of a boolean variable?

I am looking to define a function in TypeScript called 'isActive()', which I will then invoke on a button within my HTML file. Additionally, I have already declared a boolean variable named 'isActive'. In this scenario, I have two butto ...

This function CameraPreview.takePicture() does not have a return value

Recently, I've been working on updating an old app that was using an outdated version of the camera-preview plugin. The previous version had a method called setOnPictureTakenHandler which allowed me to easily retrieve the image URL. However, the new ...

Adding a ng-select field when a button is clicked

In my template, I am using ng2-select to allow users to select items. There is a button called "Add" that, when clicked, should display another select field with a list of different item categories. However, the current version of my code does not achieve ...

Using the useStaticQuery hook outside of a function component is not allowed and will result in an invalid hook call error. Remember to only call

I am currently facing an issue while trying to retrieve values using useStaticQuery from my gatsby-config.js file. Below are snippets of my code. Does anyone have any suggestions on how to resolve this problem? Thank you in advance. Repository: https: ...

The error code TS2474 (TS) indicates that in 'const' enum declarations, the member initializer must be a constant expression

Error code: export const enum JSDocTagName { Description = "desc", Identifier = "id", Definition = "meaning", } Implementing Angular 6 in conjunction with the .NET framework. ...

Strategies for managing the fallback scenario while utilizing 'createReducer' to generate a reducer and 'on' to manage actions

In the past, our reducers were created like this before the createReducer helper method was introduced: export function reducer(state: AppState, action: Action) { switch (action.type) { case "[Category List] Add Category": return { . ...

Angular refusing to refresh specific section of the UI

In my component, I am displaying charts and a table showing the latest values for each chart. This is done for each object in an array, as shown below: <div class="patient-box level-2" *ngFor="let bed of patientService.bedsLevel2" draggable="true" (dra ...

When downloading text using Angular, the file may not display new line characters correctly when opened in Notepad

When downloading text data as a .txt file in my Angular application using JavaScript code, I encountered an issue. Below is the code snippet: function download_text_as_file(data: string) { var element = document.createElement('a') eleme ...

The Art of Typing in TypeScript Classes

I am working with an interface or abstract class in TypeScript, and I have numerous classes that implement or extend this interface/class. My goal is to create an array containing the constructors of all these subclasses, while still ensuring that the arra ...