javascript - 使用共享服务将值传递给兄弟组件
问题描述
我想将选择列表中的值 - ListComponentComponent 传递给兄弟组件 - DisplayComponentComponent 并在 DisplayComponentComponent 的模板中显示该值。我想为此使用共享服务。我创建了服务,并传递了改变的价值。但是,当我想在我的显示组件中 console.log 这个值时,我什么也看不到。这是我的代码。
显示组件
export class DisplayComponentComponent implements OnInit {
val: any;
constructor(private myService: MyServiceService) { }
ngOnInit() {
this.myService.val.subscribe(result => {
this.val = result
});
}
}
列表
export class ListComponentComponent implements OnInit {
list: any;
selected: string;
constructor(private myService: MyServiceService) { }
ngOnInit() {
this.list = [
{
text: 'test1',
value: 'test1'
},
{
text: 'test2',
value: 'test2'
},
{
text: 'test3',
value: 'test3'
}
]
this.selected = this.list[0].value;
this.myService.update(this.selected);
}
getSelected(val) {
this.selected = val;
this.myService.update(this.selected);
}
}
服务
@Injectable()
export class MyServiceService {
public source = new Subject<any>();
val = this.source.asObservable();
update(input: any) {
this.source.next(input);
}
constructor() { }
}
该值应显示在此处:
<p>
{{result}}
</p>
https://stackblitz.com/edit/angular-7lhn9j?file=src%2Fapp%2Fmy-service.service.ts
解决方案
如果您想显示应用程序负载的值,您需要将主题更改为BehaviorSubject
private _onChanged: BehaviorSubject<any> = new BehaviorSubject({});
public val= this._onChanged.asObservable();
update(input: any) {
this._onChanged.next(input);
}
constructor() { }
推荐阅读
- powershell - 带有powershell命令更改字体样式的批处理文件
- grafana - Can Grafana in the same graph choose different measurement that is in influxdb with a different time range?
- html - Embedding the local external resources of an HTML page into a single HTML file
- solr - 无法从我的网页中的 Solr 服务器获取响应并出现访问控制错误
- drools - 车辆路径问题:时间窗 VRP 应考虑 TimeWindowedDepot.getDueTime()
- cordova - Best ways to automate Cordova Android App Build
- php - 在重定向到另一个页面之前显示弹出 div html
- python - Python aiohttp:在满足条件时取消异步执行
- android - 离线 webapp 有效,但不适用于移动 Android
- java - 您可以将方法设置为变量吗?