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

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

问题描述:

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

I have two components that are not parent and child components but i need to pass value from component A to component B.

示例:

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

src/abc/cde/uij/componentA.ts has variable CustomerId = "ssss"

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

need to pas that variable customerID to src/abc/xyz/componentB.ts

简单示例:

组件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

Shared service have to be placed in the same NgModule.