我有共享服务 SharedService
@Injectable()
export class SharedService {
private title = new BehaviorSubject<string>("");
currentMessage = this.title.asObservable();
constructor() { }
setData(val: string) {
this.title.next(val);
}
}
我有一个组件,我可以获得新数据
export class Fill implements OnInit {
public title;
constructor(public shared: SharedService) {
}
ngOnInit() {
this.shared.setData(this.title);
}}
和组件Info,我想要读取新数据导出类InfoComponent实现OnInit {
constructor(public shared: SharedService) {
this.title = ''; }
ngOnInit() {
console.log('i am title from info ')
this.shared.currentMessage.subscribe(title => this.title = title)
console.log(this.shared.currentMessage);
console.log(this.title);
}}
在console.log的两种情况下,我都获得了包含我需要的信息的对象 - 但我无法检索它的值 . 所以,在我的控制台上它看起来像
但如果尝试类似的东西
的console.log(this.shared.currentMessage.source.source.value);
它说 Property 'source' is protected and only accessible within class 'Observable' and its subclasses.
this.shared.currentMessage.value
this.title.value
也不起作用......我怎样才能检索一个或另一个的数据(值)?
3 回答
是 . @wostex 正确地提到了它 . 将
ngOninit
保留在构造函数的一侧,并且Update
我怀疑
currentMessage = this.title.asObservable();
是SharedService
Injectable中的无效行 .您可以编写一个方法来通过
currentMessage
方法公开this.title
公开,如下所示是的,你应该首先从构造函数中取出
ngOnInit
. 我想你想要检索BehaviourSubject
的初始状态,那么你可以在Observable上使用.getValue()函数而无需订阅流 .ngOnInit
必须在构造函数之外 .正如@micronkys指出的那样
当您订阅一个observable时,this.title的值在下一行中不可用,因为订阅是异步的,因此 Headers 剂量会更新 . 当你记录它 .
尝试在这样的模板中使用
*ngIf = "title"
UPDATE
请找一个plunker的问题希望你现在得到答案