Decorators in Angular 9 do not have the capability to support function expressions

Currently, I am working with Angular 9 and facing an issue while generating dynamic routes values during runtime. I have implemented a ComplexUrlRouter to achieve this functionality and integrated it into my Route configuration. However, I encountered the following error:

Error: src/app/app.module.ts(33,45): Error during template compile of 'AppRoutes' Expression form not supported. src/app/utility/complex.url.matcher.ts(4,10): Error during template compile of 'ComplexUrlMatcher' Function expressions are not supported in decorators Consider changing the function expression into an exported function.

Here is a snippet from my app.module.ts file:

export const AppRoutes: Routes = [
  { path: '',   component: HomeComponent, pathMatch: 'full' },
  {
    path: 'blog/:id',
    component: ArticleComponent,
    children: [
      {
        path: '',
        component: ArticleComponent
      },
      {
        matcher: ComplexUrlMatcher("title", /[a-zA-Z0-9]+/),
        component: ArticleComponent
      },
    ]
  },{
    path:'add-blog',component:AddPostComponent
  },
  {
    path:'category/:id',
    component:MenuDetailsComponent
  },
  { path: '**', redirectTo: '' }
];

And here is part of my complex.url.matcher.ts file:

import { UrlSegment, UrlSegmentGroup, Route } from '@angular/router';

export function ComplexUrlMatcher(paramName: string, regex: RegExp) {
  // Function implementation goes here
}

I have tried researching on StackOverflow for a solution but haven't been able to find one that resolves my issue. The Angular Docs URL https://angular.io/guide/aot-compiler#no-arrow-functions mentions that "In version 5 and later, the compiler automatically performs this rewriting while emitting the .js file." However, even though I am using Angular 9, the error persists.

Answer №1

Inline function calls are restricted when used with decorators in AOT compilation.

To resolve this issue, it is recommended to convert the inline function call into a function reference as shown below:

export const AppRoutes: Routes = [
  { path: '',   component: HomeComponent, pathMatch: 'full' },
  {
    path: 'blog/:id',
    component: ArticleComponent,
    children: [
      {
        path: '',
        component: ArticleComponent
      },
      {
        matcher: complexUrlMatcher,
        component: ArticleComponent
      },
    ]
  },{
    path:'add-blog',component:AddPostComponent
  },
  {
    path:'category/:id',
    component:MenuDetailsComponent
  },
  { path: '**', redirectTo: '' }
];

Additionally,

export const complexUrlMatcher = ComplexUrlMatcher("title", /[a-zA-Z0-9]+/);

export function ComplexUrlMatcher(paramName: string, regex: RegExp) {
  return (
    segments: UrlSegment[],
    segmentGroup: UrlSegmentGroup,
    route: Route) => {
    const parts = [regex];
    const posParams: { [key: string]: UrlSegment } = {};
    const consumed: UrlSegment[] = [];

    let currentIndex = 0;

    for (let i = 0; i < parts.length; ++i) {
      if (currentIndex >= segments.length) {
        return null;
      }
      const current = segments[currentIndex];

      const part = parts[i];
      if (!part.test(current.path)) {
        return null;
      }

      posParams[paramName] = current;
      consumed.push(current);
      currentIndex++;
    }

    if (route.pathMatch === 'full' &&
      (segmentGroup.hasChildren() || currentIndex < segments.length)) {
      return null;
    }

    return { consumed, posParams };
  }
}

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

Limit the elements in an array within a specified range of dates

Currently, I am working on implementing a filter functionality for a data array used in a LineChart within my Angular application using TypeScript. The structure of the data array is as follows: var multi = [ { "name": "test1", "series": [ ...

What is the best way to incorporate a component template into various modules or components?

I have developed a unique header that I wish to incorporate into various components. Here is an example of the code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-header', templateUrl: './heade ...

Can you provide instructions on how to display data in two lines within a mat-select field?

Is it possible to show selected options in mat-select with long strings in two lines within the same dropdown? Currently, the string appears incomplete. You can see an example of this issue here: incomplete string example <mat-form-field class="f ...

By using providedIn: 'root', services are automatically registered for testing

It could be due to the new functionality, but when I have a service like this: @Injectable({ providedIn: 'root' }) export class MyService {...} and my MyComponent uses it. When testing that component, I simply do this and it works! TestBed.c ...

Analyzing a sizable JSON file serving as the data source for a PostgreSQL database

Currently, I am working on a Next.js project that involves a large JSON file (~65,000 lines) serving as data for a Prisma Postgres database. The structure of the file includes entries like the following: [ { "NativeClass": "class-name", "Classes" ...

Display the content of an md-dialog with a scroll bar

I am experiencing a problem with printing a long report created using md-list displayed in a md-dialog. When I attempt to print it, only the section that is currently visible on the screen gets printed instead of the entire length of the md-list. I have at ...

update angular component after deleting an item

After deleting a contact in the table, I'm trying to refresh my contact list page but it's not working. Any suggestions? This is the list of contacts in the contact.component.ts file Swal.fire({ title: 'Do you want to delete this contac ...

Mastering the art of mocking modules with both a constructor and a function using Jest

I'm a Jest newbie and I've hit a roadblock trying to mock a module that includes both a Class ("Client") and a function ("getCreds"). The Class Client has a method called Login. Here's the code snippet I want to test: import * as sm from &ap ...

Error: The function createImageUrlBuilder from next_sanity__WEBPACK_IMPORTED_MODULE_0__ is not defined as a valid function

Having some trouble with my Next.js TypeScript project when integrating it with sanity.io. I keep getting an error saying that createImageUrlBuilder is not a function. See screenshot here Here is the code from my sanity module ...

Can we determine the type signature of useCallback for an event handler by inference?

Currently, I am working with TypeScript and React to implement a callback function using an arrow function on a Material UI <Select> component: import React from 'react'; import MenuItem from '@material-ui/core/MenuItem'; import ...

converting an angular object into a string representation

I stumbled upon this guide: . and it includes the following piece of code: import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl ...

Disabling the intellisense feature for locale suggestions in Monaco is recommended

Switch the keyboard language to a different one (in this case Japanese using alt + shift), and when typing in Monaco editor, an intellisense menu appears with options to remove and search. Monaco Editor Version: V0.33.0 https://i.stack.imgur.com/SIyeV.pn ...

Tips on ensuring that the Angular frontend waits for the response from an Express REST call

Upon initializing my user Component, I want to trigger a REST-Call so that the user profile is displayed when the page loads. The process works smoothly as the component communicates with the service, which in turn contacts my express backend to make the n ...

Guide to defining a typescript class property using an index signature

type TField = { field1: string; field2: boolean; field3: TMyCustom; } class Test1 { // I opt for using TypeScript's index signature to declare class fields [key: keyof TField]: TField[typeof key] // Instead of individually declaring each ...

Angular Notification not visible

I have been attempting to display a notification after clicking a button using the angular-notifier library (version: 4.1.1). To accomplish this, I found guidance on a website called this. Despite following the instructions, the notification fails to app ...

Version 5 of angularfie2 is encountering an issue where the type 'Observable<{}[]>' cannot be assigned to the type 'Observable<any[]>'

Encountering an error while using angularfire2 version 5: The error reads: "Type 'Observable<{}[]>' is not assignable to type Observable < any [] >." Code snippet: exercisesList$: Observable <any[]>; ionViewDidLoad() { ...

Navigate to the logout page upon encountering an error during the request

I recently upgraded our application from angular 2 to angular 5 and also made the switch from the deprecated Http module to the new HttpClient. In the previous version of the application, I used the Http-Client to redirect to a specific page in case of er ...

The Angular Material Autocomplete component fails to show items upon upgrading the angular/material package to the newest version

Issue with Angular Material Autocomplete component not displaying items after updating angular/material package to the latest version. The autocomplete was functioning correctly with "@angular/material": "^2.0.0-beta.10" but encountered issues when update ...

Some files are missing when performing an npm install for a local package

My project is structured like this: ├── functions/ │ ├── src │ ├── lib │ ├── package.json ├── shared/ │ ├── src │ | ├── index.ts | | ├── interfaces.ts | | └── validator_cl ...

Using jest-dom without Jest is definitely an interesting challenge that many developers may

Can anyone help me with extending Typescript interfaces? I have come across a situation that I am trying to solve. In my tests, I am utilizing expect without using Jest directly (I installed it separately and it functions properly). Now, I am interested ...