在两个angular2组件打字稿文件之间传递值 [英] Passing value between two angular2 component typescript files
本文介绍了在两个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
.
这篇关于在两个angular2组件打字稿文件之间传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文