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 setting up a system where PHP serves as the backend and Angular acts as the

I am working on a project that utilizes Angular as the front end and PHP as the back end. Both are installed in separate domains, with the PHP project fully completed and operational. I have created an API in PHP which I plan to call from Angular. My ques ...

Manipulate md-select options with Angular using setValue

My goal is to update a select option, but I'm having trouble getting it to work properly. When I use this.eventForm.controls.venue.setValue(event.venue.name);, the value of venue changes to match event.venue.name. However, the select option itself doe ...

Is the tooltip display for Typescript types in VSCode reliable? No need for unnecessary type assertions

Exploring the concept of const assertions in TypeScript Looking at the array allDeviceTypes depicted below, VSCode indicates it has a return type of string[] when hovering over the variable name. https://i.sstatic.net/gIYch.png However, upon using a con ...

Emit Observables within deeply nested callback functions

Hey there! I'm currently working on a web app using Angular2/4 and I've encountered an issue with Observables. My goal is to call a function within a component and then have some code executed once that function completes. Here's the releva ...

Incorporating Firebase administrator into an Angular 4 project

Currently encountering an issue while trying to integrate firebase-admin into my angular project. Despite my efforts, I am unable to resolve the error that keeps popping up (refer to the screenshot below). https://i.stack.imgur.com/kdCoo.png I attempted ...

What are the advantages of utilizing NGRX over constructor-injected services?

Have you ever wondered about the benefits of using NGRX or NGXS for an Angular application instead of constructor injected services to manage component IO? Is it simply to prevent mutation of component properties references without replacing the entire pr ...

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 ...

The nested fields in PayloadCMS GraphQL are appearing as null

When using the PayloadCMS GraphQL plugin, I encountered an issue with the type: "relationship" fields always returning null, no matter what I tried. My goal is to create a simple blog without any complexities. Despite reaching out for help in the ...

Issue with Figma React plugin's PostMessage functionality not behaving as anticipated

I am currently working on developing a plugin for Figma, following the react example provided on their GitHub page: https://github.com/figma/plugin-samples/tree/master/react One of the functionalities I have implemented is a button that triggers a specifi ...

Running a Spring Boot backend alongside multiple frontends on the same Tomcat server

I have a unique scenario where I have access to only one Tomcat server and need to set up the following components: A Spring Boot service that handles CRUD operations on a database through a REST API 2-3 distinct Angular frontends that interact with the R ...

Troubleshooting Issue with Angular 5: Inability to Hide Elements for Non-Authenticated Users

Below is the code from app.component.html <nav class='navbar navbar-default'> <div class='container-fluid'> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-targ ...

Exploring File Read and Write Functionality in Angular 4

I want to develop an offline Task List in Angular 4. However, I am facing difficulty in finding a method to save data in a file on the client side using JavaScript or Angular. My current approach involves using browser's localStorage, but it is slow ...

When transitioning between views in Angular App, it freezes due to the large data response from an HTTP request

I am encountering an issue with my Angular 9.1.11 application where it freezes after navigating from one page to another (which belongs to a different module with lazy loading). Here is the scenario: There is an action button called View Report that re ...

``Is there a specific location where I can access the Microsoft Azure msal sign-up feature within Angular

My current Angular version is 5.2.0 and I am struggling to find a tutorial on how to incorporate Azure MSAL for new user sign-up using a Microsoft account. If anyone has any resources or examples on how to achieve this integration without having to update ...

Challenges with slow performance in Ionic application when handling extensive amounts of data

We're facing performance issues with our ionic angular contact management app. The app experiences severe slowdown as the number of contacts increases, affecting taps, scrolls, and overall responsiveness. Despite utilizing offline storage to store da ...

What is the significance of parentheses when used in a type definition?

The index.d.ts file in React contains an interface definition that includes the following code snippet. Can you explain the significance of the third line shown below? (props: P & { children?: ReactNode }, context?: any): ReactElement<any> | nu ...

Utilize mapGetter and mapMutations in Vuex with TypeScript without the need for class-style components syntax

After completing a project in Vue, I found myself getting a bit confused without static types. To address this, I decided to incorporate TypeScript into my project while still maintaining the traditional way of writing code, without classes and decorators. ...

Angular9 displays a variable as undefined

As a newcomer to Angular 9, I have been encountering some issues lately. Specifically, while using Ionic 5 with Angular 9, I am facing an error where a variable appears as undefined when I try to console.log it. Please bear with me as I explain the situati ...

Is it possible to create a map of functions that preserves parameter types? How can variadic tuple types in TypeScript v4 potentially enhance this

Initially, I faced a challenge when trying to implement a function similar to mapDispatchToProps in Redux. I struggled with handling an array of functions (action creators) as arguments, but managed to come up with a workaround that works, although it feel ...

Issue with Socket.io Client: Consistently receiving error messages for an incorrect

Here is the server-side code: import http from 'http'; import Koa from 'koa'; import { Server } from 'socket.io'; (async () => { const app = new Koa(); var server = http.createServer(app.callback()); var io = new Se ...