angular2 - Pass value from parent route to child route

前端 未结 2 1414
無奈伤痛
無奈伤痛 2021-01-13 01:04

I have a route called home and it has three child routes, documents, mail and trash. In the home route component it has a variable called \'user\'. I know there are a few wa

相关标签:
2条回答
  • 2021-01-13 01:28

    You may use a common service to pass data like explained in the Angular Documentation

    Basically you may create a Service which will have a user object, which can be updated once your parent route gets loaded or with some action on parent component.

    UserService

       import { Injectable } from '@angular/core';
       import { Subject }    from 'rxjs/Subject';
    
       @Injectable()
       export class UserService {
         // Observable user 
         user = new Subject<string>();
       }
    

    And then when the child route component gets loaded you may retrieve the value from the Service.

    HomeComponent

     @Component({
       ... 
     })
     export class HomeComponent{
       ... 
       constructor(private userService:UserService ){}
       someMethod = () =>{
          this.userService.user.next(<pass user object>);
       }
     }
    

    MailComponent

     @Component({
       ... 
     })
     export class HomeComponent{
       ... 
       constructor(private userService:UserService ){
         this.userService.user.subscribe(userChanged);  
       }
    
       userChanged = (user) => {
         // Do stuff with user
       }
     }
    

    Service object will be same instance in child if you add the provider in the parent.

    0 讨论(0)
  • 2021-01-13 01:31

    Check out :- https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array

    You can pass data while changing routes on click as :-

    <a [routerLink]="['/crisis-center', { foo: myVar }]">Crisis Center</a>
    
    0 讨论(0)
提交回复
热议问题