learning how to transfer a value between two different components in React

I have 2 components.

First: component.ts

@Component({
    selector: "ns-app",
    templateUrl: "app.component.html",
})
 export class AppComponent implements OnInit {
    myid: any;
    myappurl: any;
    constructor(private router: Router, private auth: LoginService) {
    }
    ngOnInit() {
        if (this.auth.isAuthenticated()) {
            return true;
        }
        handleOpenURL((appURL: AppURL) => {
            console.log('Got the following appURL', appURL);
            this.myappurl = appURL
            console.log(this.myappurl)
            let url_1 = this.myappurl.toString();
            let url_id = url_1.split("/").reverse()[0];
            this.myid = url_id
            let LS = require("nativescript-localstorage");
            LS.setItem(this.myid)
            this.router.navigateByUrl('/test/resetPasswordRequest', this.myid); //show correct this.myid
        }); 
    console.log('this.myid', this.myid)  // show null

     }
}

.html

<page-router-outlet></page-router-outlet> 

Second: another component. I wish to retrieve this.myid and utilize it in a different component.

export class ResetPassIdComponent implements OnInit {
      constructor() {}
      ngOnInit(){
      this.resetPasswordForm = this.fb.group({
      'password': new FormControl('', Validators.required),
      'myid': new FormControl('', Validators.required)
       });
      }
onReset() {
console.log(this.resetPasswordForm.value)
  }
    }

routing.ts

{ path: 'resetPasswordRequest', component: ResetPassIdComponent }

Any suggestions on how to obtain this.myid in ResetPassIdComponent?

Thank you

Answer №1

If you're looking to update your password, there are two options available: utilize A service or pass it through a specific route.

 this.router.navigate(['/test/resetPasswordRequest', this.myid]);

You can then handle the resolution from another component like this:

export class ResetPassIdComponent implements OnInit {
  constructor(private router:Router) {}
  ngOnInit(){
    let param = this.router.routerState.root.queryParams 
  }
}

Answer №2

If you want to pass an ID using route navigation, make sure to verify that the value of myId is correct before moving to another page.

this.router.navigate(['/test/resetPasswordRequest', this.myid]);

To retrieve it in a different component, you can do the following:

import { ActivatedRoute, Params } from '@angular/router';

export class ResetPassIdComponent implements OnInit {

  id: any

  constructor(
     private route: ActivatedRoute
  ) {}

  ngOnInit(){
     this.route.params.subscribe((params: Params) => { this.id = params['myid']; });
  }
}

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

Tips for enhancing the FastifyRequest interface with a new property without erasing existing information in a declaration file

What is the method to integrate a property into an interface via declarations, while avoiding full object overwriting? declare module 'fastify' { interface FastifyRequest { user: User; } } //auth.ts ... const user = jwt.verify( ...

Exploring MongoDB files easily using Angular

I am currently working on implementing a user search feature using Angular to query users from a MongoDB collection. The function on the server side is already operational and functioning correctly with Postman. However, I encountered an error on the clien ...

An issue has been detected by Zone.js where the ZoneAwarePromise `(window|global).Promise` has been unexpectedly replaced

I have recently integrated the Angular2 quickstart code into my existing webpack setup, but I seem to be facing an issue where something is interfering with the promise from zone.js, resulting in an error. Based on my research on Stack Overflow, it appears ...

Best Practices for Architecture and Routing in Angular 8 (suggestions)

As a newcomer to Angular, I find myself grappling with the recommended architecture for my project. In an effort to streamline my inquiry, I will structure it in the form of choosing between options A or B and exploring how to implement that choice. Specif ...

What is the best way to iterate over JSON data from an endpoint that contains multiple nested arrays using the .map() method?

Seeking to showcase weather API data from: () import Image from "next/image" interface Hour { time_epoch: number time: string temp_c: number temp_f: number is_day: number wind_mph: number wind_kph: number wind_deg ...

Having difficulty incorporating an input value into an Angular function

For a school project, I am creating a login form using Angular. Below is the HTML code: <input type="text" ng-model="username" name="username" /> <input type="text" ng-model="password" name="password" /> <button (click)="submit(username, pa ...

Change the background color of a MUI ToggleButton based on a dynamic selection

const StyledToggleButton = styled(MuiToggleButton)(({ selectedColor }) => ({ "&.Mui-selected, &.Mui-selected:hover": { backgroundColor: selectedColor, } })); const FilterTeam = (props) => { const [view, setView] = ...

Using TypeScript with Node.js and Sequelize - the process of converting a value to a number and then back to a string within a map function using the OR

Currently, I am facing a challenge in performing addition on currency prices stored as an array of objects. The issue arises from the fact that the currency type can vary among 3 different types within the array of objects. The main hurdle I encounter is ...

The installation process for npm encountered an error when trying to run the [email protected] install script

Attempting to run npm install for an Angular project is presenting a challenge: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a1b4b6a586f7e8f4f6e8f6">[email protected]</a> install D:\professional-wor ...

When zooming out, Leaflet displays both tile layers

I'm currently working on integrating two tile layers along with a control for toggling between them. Below is the code snippet I am using: const layer1: L.TileLayer = L.tileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', { ...

How can I utilize Angular services to transfer a count value to the Component?

I've been working on creating a coin counter for my application by developing a service specifically for counting coins. However, when I tried to use this service in one of my components where the count function is triggered, I encountered some diffic ...

Tips on refining API response using Angular 2's HTTP module

This is the data I received from my transactions API: [{ "id": 1, "description": "Sandwich", "date": "2017-09-01", "category": "Take away", "tags": ["Holidays"], "amount": -2 },{ "id": 2, "description": "Wage", "date": "2017-08- ...

Encountering difficulty when trying to define the onComplete function in Conf.ts. A type error is occurring, stating that '(passed: any) => void' is not compatible with type '() => void'.ts(2322)'

I have been developing a custom Protractor - browserstack framework from the ground up. While implementing the onComplete function as outlined on the official site in conf.ts - // Code snippet to update test status on BrowserStack based on test assertion ...

Angular - Automatically filling in an empty input field upon dropdown selection

My goal is to create a DropdownBox that will automatically fill input fields based on the selected value. For example, selecting "Arnold" from the dropdown will populate another textbox with "Laptop". How can I accomplish this? { name:'Arnold', i ...

How to use sinon to create a mock for an independently imported function

Is there a way to successfully mock the axios import using sinon and then set expectations? Here is my attempted code: import axios from 'axios'; axiosMock = sinon.mock(axios); However, the expectation does not pass: describe('Custom test ...

Universal loading screen across all components

I am currently implementing a loading screen for this component in conjunction with the fetch method. My concern is whether I will need to replicate the same loading logic used in the example for every component that utilizes the fetch() method, or if the ...

Using Angular to parse intricate JSON data

Need help parsing an http request in the following format: [ { "id": 1, "date": "2022-01-13T00:00:00.000+00:00", "time": "2022-01-13T21:21:21.000+00:00", "office&quo ...

Angular 2 ngIf displaying briefly before disappearing

Encountering a strange issue with an Angular 2 ngIf statement where it appears on the page for a brief moment and then disappears. The content is visible, but it doesn't remain on the page. I suspect it might be related to some asynchronous behavior. ...

Tips for addressing the error "Ensure each child in a list has a distinctive 'key' prop" in a React function using TypeScript

Encountered the following warning: Warning: Each child in a list should have a unique "key" prop. Inspect the render method of TabContext. Refer to https://reactjs.org/link/warning-keys for more details. in TabForGroupInList (at Product.tsx:148) ...

How to Programmatically Assign Bootstrap Class to an Element Using Angular 2

I am working on a page with several input boxes that need to be flagged for certain criteria. <div class="form-group"> <label class="d-block">Allowance Type</label> <div class="input-group"> ...