简体   繁体   English

Angular2中的共享服务和可观察的BehaviourSubject

[英]Shared service and Observable, BehaviourSubject in Angular2

I have a shared service SharedService 我有一个共享服务SharedService

@Injectable()
export class SharedService {
  private title = new BehaviorSubject<string>("");
  currentMessage = this.title.asObservable();
  constructor() { }
  setData(val: string) {
    this.title.next(val);
  }
}

I have a component, where I get new data 我有一个组件,可以在其中获取新数据

export class Fill implements OnInit {
public title;

  constructor(public shared: SharedService) {
  }
  ngOnInit() {
this.shared.setData(this.title);
}}

And the component Info, where I want read new data export class InfoComponent implements OnInit { 组件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);
}}

In both cases of console.log I get Objects, that contains information, that I need - but I can't retrieve value of it. 在console.log的两种情况下,我都获得了包含所需信息的对象-但我无法检索其值。 So, on my console it look like 因此,在我的控制台上,它看起来像 来自控制台的消息

But if try something like 但是如果尝试类似

console.log(this.shared.currentMessage.source.source.value); console.log(this.shared.currentMessage.source.source.value);

it says Property 'source' is protected and only accessible within class 'Observable' and its subclasses. 它说属性“源”受到保护,并且只能在“可观察”类及其子类中访问。

this.shared.currentMessage.value
this.title.value

doesn't work also... How could I retrieve data (value) of one or another? 也不起作用...如何检索一个或另一个的数据(值)?

Yes. 是。 @wostex mentioned it correctly. @wostex正确地提到了它。 Keep ngOninit out side of the constructor function and, ngOninit放在构造函数的外面,

this.shared.currentMessage.subscribe(title => {

     this.title = title;
     console.log(this.title)
})

ngOnInit has to be Outside the constructor. ngOnInit必须在构造函数之外。

And as pointed by @micronkys 正如@micronkys所指出的

As you are subscribing to a observable the value of this.title is not available in the next line as the subscribing is async and so the title dosent get updated . 当您订阅一个可观察对象时,由于订阅是异步的,因此下一行中this.title的值不可用,因此标题剂量得到了更新。 when you log it. 当您登录时。

try and use *ngIf = "title" in the template like this 尝试在模板中使用*ngIf = "title"

<div *ngIf = "title">
  {{title}}
</div>

UPDATE 更新

this.shared.currentMessage.subscribe((title) => {
                          this.title = title;
                          console.log(this.title)
}

Please find a plunker for the problem hope you get the answer now 请为该问题找到一个小帮手 ,希望您现在能得到答案

Update 更新资料

I suspect currentMessage = this.title.asObservable(); 我怀疑currentMessage = this.title.asObservable(); is invalid line inside your SharedService Injectable. SharedService注入对象内是无效行。

You could write a method to expose this.title expose by currentMessage method like below 您可以编写一个方法来暴露this.titlecurrentMessage方法暴露,如下所示

@Injectable()
export class SharedService {
  private title = new BehaviorSubject<string>("");
  //below line was wrong.
  //currentMessage = this.title.asObservable();
  currentMessage(){
     return this.title.asObservable();
  }
  constructor() { }
  setData(val: string) {
    this.title.next(val);
  }
}
//Usage
console.log(this.shared.currentMessage().getValue());

Yes, you should first take out ngOnInit from constructor function. 是的,您应该首先从构造函数中删除ngOnInit I supposed you want to retrieve initial state of your BehaviourSubject , so then you could use .getValue() function on that Observable without subscribing to stream. 我以为您想检索BehaviourSubject初始状态,因此您可以在该Observable上使用.getValue()函数,而无需订阅流。

console.log(this.shared.currentMessage.getValue());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM