How can data be transferred between controllers in Angular 2 without using URL parameters or the $state.go() function?

I've encountered an issue where I need to pass a parameter from one controller to another without it being visible in the URL. I attempted to do so with the following code:

this.router.navigate(['/collections/'+this.name], {id: this.id});

However, I'm unable to access the parameter on the other controller. I also tried the following approach:

    {
      path: 'collection/:city',
      component: Component,
      data : {id : null}
    }

But my question is, how can I dynamically pass the id since it's not available in the routing file? Is there a way to pass it from the component?

In AngularJS 1.5, we utilized the params hash to conceal the id from the URL.

$state.go('collection', {id: 10})

 state('collection', {
    url : '/collection',
    params : {
        id : null,
    },
    templateUrl : templatesDir + 'collection.html',
    controller : 'collectionController',
})

My question now is whether there is a similar method in AngularJS 2.

Thank you!

Answer №1

To allow multiple components to share the same object, a singleton object must be created.

  • One approach is to use a Service and @injector in Angular2. @injector
  • Another method is to create static members within a class and access them from another class by referencing the class name.

These are the two main ways to achieve this shared object functionality.

Answer №2

If you need to pass data between controllers, one effective way is to utilize a factory or service. By storing the data in a factory, you can access it as a singleton object (but keep in mind this only lasts until a refresh occurs).

The recommended approach for storing data in a factory is to make use of getter and setter objects.

For more methods on sharing data between Angular components, check out the following resource:

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

Issue with retrieving JSON data in chart object: Error reading property 'length' of undefined in Angular/ng2-charts

     I have successfully retrieved JSON data in the following format:    [2193,3635,8417,0] The data is coming from localhost:8080. I aim to utilize this dataset for displaying a pie chart. Below is the code snippet from one.html: <div> ...

Changing the order of a list in TypeScript according to a property called 'rank'

I am currently working on a function to rearrange a list based on their rank property. Let's consider the following example: (my object also contains other properties) var array=[ {id:1,rank:2}, {id:18,rank:1}, {id:53,rank:3}, {id:3,rank:5}, {id:19,r ...

Necessary to retrieve and parse a remote file via its URL, converting the data into JSON format

For my current project, I am required to retrieve a CSV file from a URL like this link and convert it to JSON. I am familiar with reading local files using an input tag, but need assistance with this task. ...

Ways to adjust the ngx-pagination color scheme?

I am looking to customize the background color of ngx-pagination Here is my current code: <pagination-controls class="custom-pagination" id="indicadorPaginationResults" (pageChange)="p=$event" maxSize="9" directionLinks="true" autoHide="true" previ ...

Exploring the power of Vue.js reactivity using Object.defineProperty in a TypeScript environment

Currently, I am in the process of developing a TypeScript class to manage form submissions and handle server errors: export default class Form<Model> { private readonly original: Model private changes: Partial<Model> constructor(d ...

Typescript threw an error stating "Cannot access properties of an undefined object" in the React-Redux-axios

As a backend developer, I am not very familiar with frontend development. However, for my solo project, I am attempting to create some frontend functionalities including user login right after setting the password. Below is the code snippet from UserSlice. ...

Bidirectional data binding of JSON object in Angular

As a newcomer to Angular, I am currently working with Angular v.8 and have a JSON map in my component. My goal is to use this map to generate input fields in HTML, with the keys as field labels and values as input values. Although I have successfully itera ...

How can you line up various form elements, like pickers, in a row using Material UI?

As someone new to material ui, I haven't come across a solution for my specific issue yet. While there are similar questions, none seem to address the problem of aligning different form field types. My observation is that the material ui date picker ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

How can a custom event bus from a separate account be incorporated into an event rule located in a different account within the CDK framework?

In account A, I have set up an event rule. In account B, I have a custom event bus that needs to act as the target for the event rule in account A. I found a helpful guide on Stack Overflow, but it was specific to CloudFormation. I am providing another a ...

Enhancing Angular 4 classes with dependency injection techniques

Currently utilizing angular 4 and angular cli for my project development. I have created some classes that serve as the base for my components! However, as the constructors of these classes grow during development, I find myself in a phase where I need to ...

The fixed header option is not available for the CdkVirtualScrollViewport

Looking for a solution in my Angular application where I need to keep the table header at a fixed position while displaying the scrollbar only on the body part. Currently, I am utilizing the CdkVirtualScrollViewport library in Angular to render the table c ...

Experimenting with a TypeScript function containing a subscription operation

Currently, I am experimenting with Jasmine/Karma while working on an Angular 4 project. The issue I'm facing involves testing a function that seems to have trouble setting the 'name' property: https://i.stack.imgur.com/3q49i.jpg The assign ...

When using Angular and Express together, the session is not continuous as each new request generates a fresh session

Unique Question I have encountered an issue with passport.js while trying to implement authentication in my express application. When I use req.flash('message', 'message content') within a passport strategy, the flashed information see ...

Extracting the "defined" type from a TypeScript property during runtime

My current task Presently, I am iterating through the keys of an object and transferring their values to another object. interface From { [key: string]: string; } let from: From = { prop1: "foo", prop2: "23", }; interface To { [key: str ...

Discover the power of debugging Typescript in Visual Studio Code with Gulp integration

I've been working on setting up an express/typescript/gulp application, and while it's functional, I'm struggling to debug it using source-maps. Here is how I've set it up: Gulp File var gulp = require('gulp'), nodemon ...

(Angular4 / MEAN) Making a Request to Local API Yields an Empty Response Body

I'm attempting to send data to an Items API, like this: "data": { "title": "stack", "notes": "asdsad", "time": "19:02", "meridian": "PM", "type": "Education", "_id": "5a2f02d3bba3640337bc92c9", ...

What is the proper way to manage the refresh token on the client's end within a JWT system?

Curious about what exactly occurs on the client side when the refresh token expires. Is the user directed to a login page and remains logged in, or does the client side log them out automatically? My understanding is that the refresh token is saved in an ...

Steps for preloading a user prior to the page loading

Main Concern I currently have an Auth Provider set up in my application that wraps around the entire _app.tsx file. This allows me to utilize the "useAuth" hook and access the user object from any part of the app. However, I am facing an issue when using ...

Is it necessary for the version of the @types packages in TypeScript to match their non-types packages?

Are @types and untyped packages versioned the same way? npm i bluebird @types/bluebird -S returns "@types/bluebird": "^3.5.0", "bluebird": "^3.5.0", This seems logical. npm i request @types/request -S yields "@types/request": "0.0.41", "request": "^2. ...