在两个angular2组件打字稿文件之间传递值

时间:2016-10-11 15:54:35

标签: javascript angularjs angular typescript web-frontend

我有两个不是父组件和子组件的组件,但我需要将值从组件A传递到组件B.

示例:

src / abc / cde / uij / componentA.ts有变量CustomerId =“ssss”

需要将变量customerID传递给src / abc / xyz / componentB.ts

4 个答案:

答案 0 :(得分:4)

简单示例:

组件A:

@Component({})
export class ComponentA {
    constructor(private sharedService : SharedService) {}

    sendMessage(msg : string) {
       this.sharedService.send(msg);
    }
}

组件B:

@Component({})
export class ComponentB {
    constructor(private sharedService : SharedService) {
       this.sharedService.stream$.subscribe(this.receiveMessage.bind(this));
    }

    receiveMessage(msg : string) {
       console.log(msg); // your message from component A
    }
}

共享服务:

@Injectable()
export class SharedService {
    private _stream$ = new Rx.BehaviorSubject("");
    public stream$ = this._stream$.asObservable();

    send(msg : string) {
      this._stream$.next(msg);
    }
}

共享服务必须放在同一个NgModule

答案 1 :(得分:0)

在您的服务上定义setMyProperty()getMyProperty()。然后使用Component A中的值setMyProperty,然后使用getMyProperty返回值...

您必须将服务注入两个组件。

答案 2 :(得分:0)

你可以试一试。它非常简单直接。

我只是按照THIS示例进行了一些更改,以便它可以是兄弟姐妹而不是父母/孩子。

我-service.service.ts

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class MyService {
  // Observable string sources
  private myAnnouncedSource = new Subject<string>();

  // Observable string streams
  myAnnounced$ = this.myAnnouncedSource.asObservable();

  // Service message commands
  announceItem(item: string) {
    this.myAnnouncedSource.next(item);
  }
}

我-comp1.component.ts

import { Component }          from '@angular/core';
import { MyService }     from './my-service.service';
@Component({
  selector: 'my-compA',
  template: `...`,
  providers: [MyService]
})
export class MyComponentA {

  constructor(private myService: MyService) {

  }
  announceToOtherComps() {
    let sharedItem = "shibby";
    this.myService.announceItem(sharedItem);
  }
}

我-comp2.component.ts

import { Component, Input, OnDestroy } from '@angular/core';
import { MyService } from './my-service.service';
import { Subscription }   from 'rxjs/Subscription';
@Component({
  selector: 'my-compB',
  template: `...`,
  providers: [MyService]
})
export class MyComponentB implements OnDestroy {

  sharedItem = '<no data>';
  subscription: Subscription;

  constructor(private myService: MyService) {
    this.subscription = myService.myAnnounced$.subscribe(
      item => {
        this.sharedItem = item;
    });
  }

  ngOnDestroy() {
    // prevent memory leak when component destroyed
    this.subscription.unsubscribe();
  }
}

答案 3 :(得分:0)

<component-a [id]="product.id"></component-a>

在component-a ts文件中。使用如下

export class ComponentA implements OnInit {

@Input() // <------------
 id: number;

 (...)
}