首页 文章

Angular2中的共享服务和Observable,BehaviourSubject

提问于
浏览
0

我有共享服务 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 回答

  • 0

    是 . @wostex 正确地提到了它 . 将 ngOninit 保留在构造函数的一侧,并且

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

    Update

    我怀疑 currentMessage = this.title.asObservable();SharedService Injectable中的无效行 .

    您可以编写一个方法来通过 currentMessage 方法公开 this.title 公开,如下所示

    @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());
    

    是的,你应该首先从构造函数中取出 ngOnInit . 我想你想要检索 BehaviourSubject 的初始状态,那么你可以在Observable上使用.getValue()函数而无需订阅流 .

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

    ngOnInit 必须在构造函数之外 .

    正如@micronkys指出的那样

    当您订阅一个observable时,this.title的值在下一行中不可用,因为订阅是异步的,因此 Headers 剂量会更新 . 当你记录它 .

    尝试在这样的模板中使用 *ngIf = "title"

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

    UPDATE

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

    请找一个plunker的问题希望你现在得到答案

相关问题