【发布时间】:2017-05-23 09:51:23
【问题描述】:
为了在几个组件之间传递数据,我创建了一个服务:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class Services {
private messageSource = new BehaviorSubject<string>("lol");
currentMessage = this.messageSource.asObservable();
constructor() {
}
changeMessage(message: string) {
this.messageSource.next(message);
console.log(message);
}
}
我为包含传递的数据创建字符串消息源,并为 Observable 创建当前消息。之后我创建函数来更改这些数据。
所以现在,在一个组件中的 ngOnInit() 中,我写道:
this.data.currentMessage.subscribe(message => this.message = message);
并在组件消息中定义:字符串保存消息。
在我做的功能中:
selectNews(news) {
this.data.changeMessage("lol3"); // string for test
}
然后,我想在其他组件中获取这个字符串
所以再次在 ngOnInit 中,我复制同一行并定义消息。但是这里的控制台日志显示了函数执行操作之前的字符串......
问题出在哪里?
编辑 摆弄所有完整的代码:
【问题讨论】:
-
你的帖子结尾不是很清楚,很难帮忙。也许你可以分享你的其他组件的代码?
-
我用代码添加小提琴:)
-
这个问题真是一团糟……没有 POST 或 GET……你想从服务中Emit。我只是回答类似的问题 - stackoverflow.com/a/44130831/5452965 你需要在组件之间发出消息
标签: javascript angular typescript rxjs