struggling to set default values for route parameters in Angular

I'm struggling with setting default values for my route parameters within the ts class of my component. I would like genreId to default to null, while monetization, sortBy, and page should have preset values. I'm unsure whether I should handle this in ngOnInit or if it should be done differently within my app routing module.

export class MoviesPageComponent implements OnInit {
  movies?: MovieData;
  genreId?: string | null = null;
  monetization?: string | null;
  sortBy?: string | null;
  page?: string | null;
  constructor(private getMovies: GetMoviesService,
              private route: ActivatedRoute) { }
  ngOnInit(): void {
    this.route.queryParamMap.subscribe((params: ParamMap) => {
      this.genreId = params.get('genreId')
    })
    this.route.paramMap.subscribe((params: ParamMap) => {
      this.monetization = params.get('monetization');
      this.sortBy = params.get('sortBy');
      this.page = params.get('page');
    });
    if (this.genreId === null) {
      this.getMovies.moviesData(this.monetization, this.sortBy, this.page).subscribe((movieData: MovieData) => {
        if (movieData !== undefined) {
          this.movies = movieData;
        }
      })
    }
  }
}

This is how my app routing module array is structured.

const routes: Routes = [
  {path: ' ', pathMatch: 'full', redirectTo: '/:monetization/:sortBy/:page'},
  {path: '/:monetization/:sortBy/:page/', pathMatch: 'full', component: MoviesPageComponent}
];

Answer №1

Ensure to assign default values when declaring variables and update them with received truthy values. Utilize the || operator for assignment to move to the next value if the first one is falsey. Consider using ActivatedRouteSnapshot over ActivatedRoute for accessing params.

export class MoviesPageComponent implements OnInit {
  movies?: MovieData;
  genreId?: string | null = null;
  monetization = 'default monetization';
  sortBy = 'default sort by';
  page = 'default page';
  constructor(
    private getMovies: GetMoviesService,
    private snapshot: ActivatedRouteSnapshot
  ) {}
  ngOnInit(): void {
    this.genreId = this.snapshot.queryParams['genreId'] || this.genreId;
    this.monetization =
      this.snapshot.params['monetization'] || this.monetization;
    this.sortBy = this.snapshot.params['sortBy'] || this.sortBy;
    this.page = this.snapshot.params['page'] || this.page;

    if (this.genreId === null) {
      this.getMovies
        .moviesData(this.monetization, this.sortBy, this.page)
        .subscribe((movieData: MovieData) => {
          if (movieData !== undefined) {
            this.movies = movieData;
          }
        });
    }
  }
}

On a side note, if there's no need to distinguish between null and undefined, opt for undefined and check falsy or truthy values using ! or a simple if statement. This practice can help simplify your code.

export class MoviesPageComponent implements OnInit {
  movies?: MovieData;
  genreId?: string;
  ...
  ngOnInit(): void {
    this.genreId = this.snapshot.queryParams['genreId'];
    ...
    if (!this.genreId) {
      this.getMovies
        .moviesData(this.monetization, this.sortBy, this.page)
        .subscribe((movieData: MovieData) => {
          if (movieData) this.movies = movieData;
        });
    }
  }
}

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

In a Next.js project, Typescript seems to be overlooking errors related to proptype definitions and function types

Greetings everyone! I am currently working on a project using TypeScript and have implemented various rules and elements. However, I am facing issues with type errors for functions and props. Essentially, when using any function, it is necessary to specify ...

Tips for Implementing Error Handling in Angular using Sweetalert2

On this code snippet, I have implemented a delete confirmation popup and now I am looking to incorporate error handling in case the data is not deleted successfully. confirmPopUp(){ Swal.fire({ title: 'Are You Sure?', text: 'Deleti ...

Guide to using a TypeScript interface in a JSON file with Visual Studio Code

Imagine having a TypeScript interface as follows: interface Settings { id?: number tag: string } Is there a way to ensure that all .json files within a specific directory adhere to these requirements? If VS Code does not offer this functionality, ...

An error occurred in Angular 4 where an expression was changed after it had been checked, causing a

Encountering an error and struggling to debug from the console: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'Main Bike Trails'. at viewDebugE ...

Unexpected Display Issue with Angular Select Option

My goal is to implement the Select-Option Input as depicted in the first image link here: https://i.sstatic.net/SVT8R.png However, my current output looks different and I suspect that there may be a conflict between two CSS libraries. It's worth noti ...

What is the specific purpose of the 'extend' keyword in Typescript?

Recently, I have been delving into the realm of Javascript/Typescript/React as a PHP developer. During my learning process, I encountered a few perplexing issues that I could not fully grasp. In light of this, I am reaching out to the experienced indiv ...

Pointer Cursor in CSS

I am experiencing a strange issue. When I set the cursor attribute value directly as a string like return ( <Grid item> <Card sx={{ padding: "1rem", ":hover": { cursor: "pointer" ...

Ways to specify the T (Generic type) associated with the class

I am working with a class that uses a generic type like this: SomeGenericClass<T>{ constructor(){ } } Within some of the functions, I log messages and want to refer to the current type T of the generic class in my logs. I have attempted t ...

What is the method to ensure that the option group is selectable?

Is there a way to enable the selection of an option group? <select> <optgroup value="0" label="Parent Tag"> <option value="1">Child Tag</option> <option value="2">Child Tag</option> </optgroup> ...

Angular ngx-translate Feature Module failing to inherit translations from Parent Module

Currently, I am implementing lazy loading for a feature module. I have imported TranslateModule.forChild() with extend true to load feature-specific translations. In my app.module, I am importing TranslateModule.forRoot to load common translations. The i ...

A method for increasing a counter using only an instance of a class or function without accessing its methods or properties in Javascript

Looking at the task ahead, let increment = new Increment(); I have been tasked with creating a Javascript class or function called Increment in order to achieve the following: console.log(`${increment}`) // should output 1 console.log(`${increment}`); ...

What is the process of using TypeScript to import a constant exported in JavaScript?

In the environment I'm using typescript 2.6.1. Within react-table's index.js file, there is a declaration that looks like this: import defaultProps from './defaultProps' import propTypes from './propTypes' export const React ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

Having trouble implementing the Material UI time picker because it does not meet the required DateTime format

REVISE I recently switched my dataType from DateTime to TimeSpan in my code. I have a functioning MVC version that already uses TimeSpan, and the times are posted in HH:MM format. Now, I am unsure if the issue lies with the headers set up on Axios or if it ...

Unable to generate paths in Ionic 3

I am trying to view the actual route on the URL, but I'm having trouble figuring out exactly what needs to be changed. I've been referring to the documentation at: https://ionicframework.com/docs/api/navigation/IonicPage/ However, I keep encoun ...

Problems with the duration of Shadcn Toasts (Inspired by the react-hot-toast library)

Within a 13.4 Nextjs project (app router), utilizing Typescript and TailwindCSS. I am currently exploring the usage of toasts provided by the remarkable shadcnUI Library, which draws inspiration from react-hot-toast while adding its own unique flair. Imp ...

How can I access a component variable within a foreach loop in Typescript?

Can anyone please explain how I can access a component variable within a foreach loop? Check out my code on Plunker public exampleVariable:number; test(){ console.log('fired'); var x =[1,2,3,4]; x.forEach(function (e){ th ...

Safari encountering parsing date error

My Angular application is receiving date formats from a web service in the following format: myDate = "2020-03-05T08:00:00" This translates to the fifth of March, 2020 for me For Chrome, Firefox, and IE, the format is yyyy-mm-ddThh:mm:ss However, Safar ...

Issue with Angular Jasmine: expect().toHaveBeenCalled() not functioning as expected

Seeking assistance with debugging my unit test code for testing method invocation upon a button click event. The methods are functioning correctly in the app itself but not during testing: fit('Cancel button should trigger dialog modal', () => ...

Tips on How to Customize Date Formatting for In-Cell Editing in a Kendo Grid

Currently, I am utilizing In-Cell Editing on a kendo-grid-column. The example provided here demonstrates how you can define the editor attributes for the column. For my specific column, I want to be able to edit dates, so I require a date picker. This can ...