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

如何从angular 2中的子组件中的父组件获取变量?,angular,angular2-routing,angular2-router3,Angular,Angular2 Routing,Angular2 Router3,这是Routing.ts { path: 'adminHome', component: adminHomeComponent, children: [ { path: 'users', component: UserListComponent, children: [ { path: ':id', component: EntrepriseListComponent, childre

这是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,它包含显示EnterpriseListComponent的用户和路由器出口的列表

@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} )
 }
@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);


 })    
}
@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);

}
@组件({
模板:`
用户名单

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

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);
  }
}
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');
    }
}

希望这能有所帮助。

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

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);
  }
}
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');
    }
}

希望这能有所帮助。

可能重复的不正确的不正确的可能重复的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确的不正确;此共享服务和值独立于URL路由参数。您可能要做的是在路由参数中使用正确的值,然后该路由的组件从路由参数中检索值,并使用类似于
This.Route.Params.subscribe的内容将其发送到共享服务(param=>this.sharedService.setUserId(param['userId']);
有意义吗?它不起作用,我在url上得到了这样的stg!我应该在('newValue')上放什么;此共享服务和值独立于URL路由参数。您可能要做的是在路由参数中使用正确的值,然后该路由的组件从路由参数中检索值,并使用类似于
This.Route.Params.subscribe的内容将其发送到共享服务(param=>this.sharedService.setUserId(param['userId']);
有意义吗?