Passing an object from @CanActivate() to a component in Angular 2 leads to Typescript Error

Within Angular 2, I am using a MyObjectComponent to display an array of myObjects. These myObjects are retrieved from a MyObjectService, which is called by @CanActivate.

@CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => {

    let myObjectService: MyObjectService = //get MyObjectService instance here....

    return new Promise((resolve) => {
        myObjectService.getMyObjects()
            .subscribe((myObjects) => {
               next.params['myObjects'] = myObjects;
               resolve(true);
             });
    })

In the component, I access the data with:

routerOnActivate(next) {
    this.myComponentObjectVariable = next.params.myObjects;
}

This setup functions properly, but only when the myObjects added to next.params['myObjects'] is a string.

If I attempt to add an object, I encounter a TypeScript error:

Typescript error: TS2322: Type 'any[]' is not assignable to type 'string'.

The JavaScript output works fine, but eliminating the Typescript error is desired. This issue arises due to the params object's definition in ComponentInstruction:

declare class ComponentInstruction {
    ... some other data ...
    params: {
        [key: string]: string;
    }; 
}

One potential solution could involve modifying the ComponentInstruction class, although that may seem cumbersome. Any suggestions on resolving this error message would be appreciated.

Answer №1

params should always be considered as unchangeable.

I recommend utilizing the method shown in the Plunker provided in this comment https://github.com/angular/angular/issues/4112#issuecomment-987654321 and transmitting the value through a shared service instead of route parameters.

Another option is to make use of

_router.navigate(...) and send custom route parameters through there.

In this scenario, you would also need to follow the steps outlined in the Plunker to obtain the application's Router instance.

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

Error in Angular deployment: The property "apiUrl" is missing from the object type {production: boolean}

After developing an Angular 7 App with a Laravel backend, I encountered an error while trying to build and deploy it for production. src/app/services/user.service.ts(10,32): error TS2339: Property 'apiUrl' does not exist on type '{ product ...

What is the process for creating an additional username in the database?

As a beginner frontend trainee, I have been tasked with configuring my project on node-typescript-koa-rest. Despite my best efforts, I encountered an error. To set up the project, I added objection.js and knex.js to the existing repository and installed P ...

Tips on implementing conditional validators in Angular's formBuilder

Is it possible in Angular 7.x to use formBuilder and ReactiveForms to apply a validator to a form based on the user's role? For instance, if the user has a specific role, they would be required to input certain fields. The user information is stored i ...

An in-depth guide on implementing Highcharts.Tooltip functionality in a TypeScript environment

Currently, I am trying to implement a tooltip activation on click event in Highcharts by following an example from this URL: Highcharts - Show tooltip on points click instead mouseover. The challenge I'm facing is that I am using TypeScript and strugg ...

Customizing the entire application's style based on conditions in Angular 4

Looking to implement a dark mode button for the app. Create a toggle switch for "dark mode". This switch will change a boolean value, "dark-ui", between true and false. When the app component detects dark-ui as true, add the class "dark" to a parent-leve ...

Auto-login functionality in Ionic 2 is failing to work properly on Android Nougat within the Ionic development application

I've been working on an Ionic application and have successfully implemented the login and registration functionalities using JWT. The app checks for authentication by validating the token, and if the token is missing or different from the server, the ...

What is the best way to ensure that the base class Resolver finishes before allowing the derived class Resolver to execute?

I have a situation where many of my resolvers (@angular/router Resolve) need to query the same data before executing their route-specific queries. To streamline this process, I want to create a resolver base class that resolves the initial data before the ...

Seeking assistance with printing an HTML template using a printer in Angular 2. Can anyone provide guidance on how

I have a scenario where I need to print an HTML template from within my Angular 2 component. Specifically, I want to be able to click on a print button on the same page and trigger the print function, which would display a print preview and allow the use ...

Is there a way to selectively deactivate the routerLink attribute?

I am facing a challenge in my Angular 2 project where I am unable to disable the routerLink functionality successfully. Despite trying to intercept the click event on the 'click' event with 'event.preventDefault()' and 'event.stopP ...

Angular Floating Panels: A Guide to Creating Dynamic User Interfaces

In the process of developing an angular app, I require a dock-able panel. After researching available controls online, I found them difficult to use and they compromised our screen layout. As a result, I am considering building a custom dock panel from s ...

I'm encountering a typescript error as I migrate a Paho MQTT function from Angular 1 to Angular 2 - what could be causing this issue?

When connecting to my MQTT broker, I am working on several tasks. In my Ionic 2 and Angular 2 application, I have created an MQTT provider. Here is the provider code: import { Component } from '@angular/core'; import { NavController, ViewControl ...

Splitting a string in Angular: A step-by-step guide

Is there a way to separate a string using the pipe symbol? The string I have is: Alex Santos||<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0968656c71277a68677d667a479871ab808a88878a">[email protected]</a> I on ...

Angular 6 component experiencing issues with animation functionality

I've implemented a Notification feature using a Notification component that displays notifications at the top of the screen. The goal is to make these notifications fade in and out smoothly. In my NotificationService, there's an array that holds ...

Having difficulty troubleshooting the /app router application on version 13.4.x

Having trouble debugging a server-side process in my Next.js app that uses the /app router. To reproduce the issue, simply create a new Next.js app with npx create-next-app and select the app router option. I've attempted to attach a debugger to the ...

Angular and Node integration with Firestore authentication

I need some guidance with integrating an Angular application and a Node.js API, both using Firestore (Firebase). We have encountered an issue when validating tokens for authenticated users - the token never seems to expire. Even after logging out in the An ...

Test fails in Jest - component creation test result is undefined

I am currently working on writing a Jest test to verify the creation of a component in Angular. However, when I execute the test, it returns undefined with the following message: OrderDetailsDeliveryTabComponent › should create expect(received).toBeTru ...

Issues with Angular 5 application functionality on IOS8 using Browserstack

I encountered an issue while testing my Angular 5 app on an iPhone 6 with IOS8 (Safari) and in Browserstack. The app fails to run, only showing an empty page along with a Javascript error. Any advice or suggestions on how to resolve this? https://i.sstat ...

A guide on utilizing portals in Next.js to move a child element beyond its direct parent container

Current Setup Wrapper export const ContainerComponent = () => { return (<ChildComponent/>); } Child Component export const ChildComponent = () => { return ReactDOM.createPortal( <aside> <div>{"I am a c ...

Using the useRef validation can lead to errors when trying to reference the current value against an input

Currently, the code is functioning well but an error alert from Typescript needs to be addressed. A warning pops up regarding the use of ref.current.value. ERROR 1. TS18048: 'ref.current' is possibly 'undefined'. To tackle this issue, ...

How to form an array using rxjs before the adding sequence is completed

I am currently exploring a way to utilize rxjs to achieve the following scenario: You have two observables, onAddObs and onRemoveObs. Assume that onAddObs.next() is triggered multiple times, adding "A", "B", "C". I aim to then extract ["A", "B", "C"]. .t ...