Sending dynamic information via Angular 2 routing

Passing static data to an Angular 2 route without displaying it in the URL is achievable.

However, the real challenge lies in passing dynamic data or objects using the same approach.

Answer №1

To access data in routes, you can utilize a resolver which provides the necessary information just like static data in route configurations.

For a detailed example, refer to https://angular.io/guide/router#resolve-guard

@Injectable()
export class CrisisDetailResolve implements Resolve<Crisis> {
  constructor(private cs: CrisisService, private router: Router) {}
  resolve(route: ActivatedRouteSnapshot): Promise<Crisis>|boolean {
    let id = route.params['id'];
    return this.cs.getCrisis(id).then(crisis => {
      if (crisis) {
        return crisis;
      } else { // id not found
        this.router.navigate(['/crisis-center']);
        return false;
      }
    });
  }
}
path: '',
component: CrisisListComponent,
children: [
  {
    path: ':id',
    component: CrisisDetailComponent,
    canDeactivate: [CanDeactivateGuard],
    resolve: {
      crisis: CrisisDetailResolve
    }
  },
ngOnInit() {
  this.route.data
    .subscribe((data: { crisis: Crisis }) => {
      this.editName = data.crisis.name;
      this.crisis = data.crisis;
    });
}

Answer №2

If you are looking to pass data in Angular, there are two approaches you can take:

{ path: 'some:data', component: SomeComonent }

One way is not recommended, but you can use data as a router parameter and pass it like this:

let data = {"key":"value"}
this.router.navigate(['/some', data)

The second approach involves using a service instead of passing data through route parameters. This is because passing large amounts of data through route params can be risky as the data may be visible to users.

@Injectable()
export class SomeService {
  data = {};
}

@Component({...
   providers: [SomeService]
export class Parent {
  constructor(private someService:SomeService) {}

  private click() {
    this.someService.data = {"key":"value"}
  }
}

Answer №3

To get the best solution, it is recommended to merge the insights from the following two responses:

  • Referencing Günter Zöchbauer's answer, a custom Resolver acting as a message enricher is suggested. This Resolver passes all crisis-related data to CrisisComponent when an URL ending in /crisis/15 is accessed. While this Resolver is necessary, it should be noted that OP might prefer not displaying any data in the URL.
  • In Tsadkan Yitbarek's response, the idea of using a service for data storage and communication similar to Redux/Flux stores is shared. Although considered excessive by some, having a designated storage location for information is crucial.

The optimal approach involves embedding the shared data within the Resolver itself: Since services are persistent and remain as single instances, the data can securely reside in the resolver:

// --- CrisisDetailResolve ---
// Add the following lines inside the function body:
private currentCrisisId: number | string

set(crisisId: number | string) {
   this.currentCrisisId = crisisId 
}

// Modify line 5 in CrisisDetailResolve:
 let id: number = 0 + this.currentCrisisId

// -- In your code --
// By concealing the crisis number from users, you can navigate effortlessly:
private click(crisisId : string | number) {
  // Notify the resolver about the upcoming crisis:
  this.crisisResolve.set(crisisId)  
  // Direct to CrisisDetail via CrisisResolve:
  this.router.navigate(['/crisisDetail')
  // CrisisDetail component can now access id and name through `data` during NgOnInit,
  // mirroring Günter Zöchbauer's method and Angular documentation
}

For further details, consult the Angular Docs on Routing

Answer №4

If you want to transfer dynamic information from Angular7.2, utilize the state object.

Within the Component, send data through navigateByUrl:

  public product = { id:'1', name:"Angular"};
  gotoDynamic() {
     this.router.navigateByUrl('/dynamic', { state: this.product });
  }

To retrieve the data, use history.state:

In dynamicComponent

    ngOnInit() {
           this.product=history.state;
    }  

For more details, check out: Passing Dynamic Data

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

Nested REST API calls in Angular are causing only the inner call to be returned

When retrieving a ShoppingCart with ShoppingCartItems through an outer REST call, an Observable of the ShoppingCartItems is then used to make an inner call in order to enhance the items with a Provider. After the inner call, a tap(console.log) shows that ...

Maximizing Jest's potential with multiple presets in a single configuration file/setup

Currently, the project I am working on has Jest configured and testing is functioning correctly. Here is a glimpse of the existing jest.config.js file; const ignores = [...]; const coverageIgnores = [...]; module.exports = { roots: ['<rootDir&g ...

Can you please tell me the location of the sqlite database file in Ionic 2 Cordova?

Currently, I am working with cordova-plugin-sqlite within the context of angular2 ionic2. Interestingly, despite my efforts, I have not been able to locate the database file anywhere within my project structure. Numerous attempts to resolve this issue by ...

Issue with Datepicker placement inside Modal container in Ngx-bootstrap

When we nest an Ngx-Bootstrap modal inside another modal, the datepicker container randomly opens in a different place. It seems to be caused by the inner dialog having a datepicker element. If you'd like to see an example, you can check out this dem ...

Filter an object in Typescript and retrieve a single key

Managing a set of checkboxes is essential in assigning roles to new users. While it's possible to filter and retrieve only the checked checkboxes, extracting just the "name" key poses a challenge. The current method involves filtering with a for loop ...

Adjusting the height of Google maps in Angular 4 to occupy the rest of the

I have integrated https://github.com/SebastianM/angular-google-maps into my angular 4 application. In order for the map to display properly, I need to specify the map height in CSS like this: agm-map { height: 300px; } Is there a way for the <agm-m ...

The SonarTsPlugin report is coming back clean with no issues found in the Typescript files

In my current project, I am attempting to analyze an Angular application using SonarQube. This particular project consists of a mix of JavaScript and TypeScript files. During the Sonar analysis process, I have noticed that while issues are being generated ...

Angular 2 radio button problem with model-driven form

I'm facing a challenge with getting radio buttons to function correctly in my reactive form. Below is the code for my component: export class SettingsFormComponent implements OnInit { public sForm: FormGroup; public submitted: boolean; d ...

Issue: Generated fewer hooks than anticipated. This situation could be a result of an unintentional premature return statement

view image description see image here I encountered an issue while trying to retrieve a specific item from my customer list on the first attempt. The strange behavior occurs when I search for a name not present in the table, then search for an existing en ...

Ways to verify the minimum character count in ion-textarea

What is the best way to enforce a minimum length validation for a textarea in Ionic 3? It's interesting that while maxlength seems to be working fine, minlength doesn't appear to work as expected. <ion-textarea id="emailBody" minlength="2" ro ...

Update the AngularJS (1.5) application to Angular 5

Looking for advice on transitioning an AngularJS app to Angular (in this case, version 5). I've been exploring the official documentation, but I still have some uncertainties. From what I gathered in the guide, it suggests migrating from AngularJS by ...

What is the best approach for managing and obtaining accurate JSON responses when working with PHP API and AngularJS 2 services?

Encountering a backend issue with MySQL, wherein one query is producing a specific dataset: {"candidat":[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz"," ...

Using ReactiveForms to create templates that dynamically generate recursive structures

Describing an issue I'm facing. View Example Online I have a unique JSON that needs to be transformed into a form. To achieve this, I utilized reactive forms and iterated through the JSON properties to generate either a FormGroup or FormControl like ...

Manipulating URL parameters in Angular 2

I have implemented the following code: this.router.navigate(['/app/chart', {chartColor: this.color, chartWidth: this.width}]); Upon executing this code, the URL is set to: http://localhost/app/chart;chartColor=blue;chartWidth=600 Everything s ...

Tips for ensuring all files are recognized as modules during the transition of an established NodeJS project to TypeScript

I'm diving into TypeScript as a newcomer and I am exploring the process of transitioning a large, existing NodeJS codebase that is compliant with ES2017 to TypeScript. Here's a glimpse at my tsconfig.json: { "compilerOptions": { "mo ...

What is the reason behind TypeScript's restriction on referring to const variables in type definitions?

Defining a type that restricts the input string to two possible values can be done like this: type STATE_TYPE = 'DRAFT'|'PUBLISHED' function myFunc(state: STATE_TYPE) { ... } However, when trying to define the two values as const and ...

Establishing the testing sequence for Angular 8

I've been encountering a frustrating issue where one of my tests fails at random intervals. To add some order to the debugging process, I attempted to set a seed number in the 'karma.conf.js' file and also tried setting 'random: false&a ...

Incorporating Vaadin components into an Angular2-seed project

Hi there, I've been encountering an issue while trying to integrate Vaadin elements into my Angular2 seed project. The Vaadin team has recommended that I upgrade the systemjs.config.js file by specifying the path names for Vaadin elements like this: ...

Customize the datepicker locale in Valor

Currently, I am working with Angular2 and typescript alongside the Valor datepicker. Unfortunately, the datepicker does not have the necessary locale built-in. After some research, I discovered that the essential JavaScript file containing the locale infor ...

What is the solution to fixing the Vetur/Vuelidate issue where the error message "'validate' does not exist in type 'ComponentOptions<Vue [etc.]" is displayed?

QUERY: I'm facing an issue with error 'validations' does not exist in type 'ComponentOptions<Vue [etc.] when using Vetur with TypeScript installed in VSCode. How can I resolve this? CONTEXT: I integrated Vuelidate into a single-file ...