如何从角度2中的子组件中的父组件获取变量?

时间:2017-04-08 12:43:49

标签: angular angular2-routing angular2-router3

这是Routing.ts

{
 path: 'adminHome',
 component: adminHomeComponent,
 children: [
    {
     path: 'users',
     component: UserListComponent,
     children: [
       {
         path: ':id',
         component: EntrepriseListComponent,
         children: [
           {
              path: ':id2',
              component: ListLaucauxComponent,
              children:[
                 {
                  path:':id3',
                  component:DeviceListComponent }
                        ].......

这是UserListComponent,其中包含显示EntrepriseListComponent的用户和路由器出口列表

@Component({
template :`
<h2> List of users</h2>
        <ul *ngFor="  let user of users >
            <li>{{user.firstName}}</li>
            <li>{{user}}</li>
            <li><a [routerLink]="['/adminHome/users',user.id]">L.E</a></li>
        </ul>
                <router-outlet></router-outlet> `
})
export class UserListComponent implements OnInit {
private users: User[];

constructor(private userService: UserService ) { }

ngOnInit() 
{
  this.userService.getAllUsers().subscribe(data => {this.users = data} )
 }

这是EntrepriseListComponent,它包含显示LocalListComponent的Entreprise和router-outlet的列表

@Component({
template:`
<h2>List of entreprise </h2> 
  <ul *ngFor="let entreprise of entreprises">
      <li>{{entreprise .id}}</li>
      <li>{{entreprise .name}}</li>
      <li><a [routerLink]="
['/adminHome/users/',idUser,entreprise.id]">L.L</a></li>
    </ul>
              <router-outlet></router-outlet> `
 })
export class EntrepriseListComponent implements OnInit {

constructor(private Service:EntrepriseService ,private 
route:ActivatedRoute) { }

entreprises : Entreprise[];
idUser :string ; // this what i want to get from parent

ngOnInit() { 
this.route.params.forEach(params=>{
   this.route.params.forEach(params => {
        let id = params['id'];

        this.entrepriseService.getEntrepriseByIdUser(id)
            .subscribe(data => {
                console.log(data)
                this.entreprises = data;
            })
        this.sharedService.userId$.subscribe(data => this.userId = data);
        this.sharedService.updateUserId(id);


 })    
}

这是LaucauxListComponent,其中包含用于显示DeviceListComponent的laucaux和router-outlet的列表

@Component({
template: `
<h2>List des Locaux </h2> 
<ul *ngFor="let x of laucaux">
<li>{{x.name}}</li>
<li><a [routerLink]="['/adminHome/users/',idUSer,idEntreprise,x.id]">Liste 
 Devices</a></li>
 </ul>
    <router-outlet></router-outlet>`
 })
export class ListLaucauxComponent implements OnInit {
laucaux: Laucaux[]

constructor(private ls: LoacauxService, private route:ActivatedRoute) { }
idUSer :string ;// this what i want to get from parent
idEntreprise : string ;// this what i want to get from parent

ngOnInit() {
 let id = params['id2'];

        this.loacauxService.getLaucauxByEntreprise(id)
            .subscribe(data => {
                console.log(data)
                this.laucaux = data;
            })

        //retrieve values
        this.sharedService.userId$.subscribe(data => this.iduser = data);
        this.sharedService.enterpriseId$.subscribe(data => this.identreprise 
  = data);


        //update values
        this.sharedService.updateUserId(this.iduser);
        this.sharedService.updateUserId(this.identreprise);

}

那么如何在EntrepriseListComponent中获取idUSer,在ListLaucauxComponent中获取idUSer&amp; idEntreprise

1 个答案:

答案 0 :(得分:0)

当跨路由共享数据时,最好为他们创建一个共享服务供他们使用。每个组件都可以更新共享服务中的任何相关数据,您可以使用每个组件可以订阅的Observable来接收共享数据的更新。它看起来像这样:

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
@Injectable()
export class SharedService {
  // Observable string sources
  private userIdSource = new Subject<string>();
  private enterpriseIdSource = new Subject<string>();

  // Observable string streams
  userId$ = this.userIdSource.asObservable();
  enterpriseId$ = this.enterpriseIdSource.asObservable();

  // Service message commands
  updateUserId(id: string) {
    this.userIdSource.next(id);
  }
  updateEnterpriseId(id: string) {
    this.enterpriseIdSource.next(id);
  }
}

通过使用Subject,组件只会接收组件订阅后更新的值。 IE:SharedService发出一个新的userId那么ComponentA订阅了userId$ observable。 ComponentA不会获得先前更新的值。如果您需要将任何以前的值发送到组件而不管他们何时订阅,请使用BehaviorSubject代替Subject

组件会订阅这些值并更新如下值:

export class ComponentA {

    userId:string;

    constructor(private sharedService: SharedService){}


    ngOnInit(){
        //retrieve values
        this.sharedService.userId$.subscribe(data => this.userId = data);

        //update values
        this.sharedService.updateUserId('newValue');
    }
}

希望这有帮助。