繁体   English   中英

如何在Angular4中使用行为主题

[英]How to use Behaviour Subjects in Angular4

我正在使用一项服务来保存一个值并在另一组件中使用。 这是我的服务,

 export class PageService {
  template_type$:Observable<any>;
  private myMethodSubject1 = new BehaviorSubject<any>('hi');
  constructor() { 
   this.template_type$ = this.myMethodSubject1.asObservable();
  }
  template_type(selectedType){
    this.myMethodSubject1.next(selectedType);
   //console.log(selectedType);
   }
 }

在我的职责中,我向这项服务传递价值,

 this.pService.template_type('one');

在同一个组件的另一个功能中,我称此服务以获取价值

 this.pService.template_type$.subscribe(data=>{
  console.log(data);
})

但是它首先返回“ hi”,在函数调用后返回值..但是我首先需要值...代码中是否有错误?

听起来您不想使用BehaviorSubject ,而是要使用ReplaySubject(1)

private myMethodSubject1 = new ReplaySubject<any>(1);

没有初始值。

暂无
暂无

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

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