web site
web site

Reputation: 99

how to use a value from one component to another component

I have 2 component.

First: component.ts 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 want to get this.myid and use in another 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 idea pelase,how to get this.myid in ResetPassIdComponent ?

Thanks

Upvotes: 0

Views: 540

Answers (2)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41447

You can either use A service or pass it through route

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

And resolve it from another component

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

Upvotes: 3

Devang Patel
Devang Patel

Reputation: 1843

You can use route navigation to pass an ID. However make sure you get proper value of myId before routing to another page.

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

To receive it in another component you can use 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']; });
  }
}

Upvotes: 0

Related Questions