简体   繁体   English

如何在Angular4中使用行为主题

[英]How to use Behaviour Subjects in Angular4

I am using a service to save one value and used in another component. 我正在使用一项服务来保存一个值并在另一组件中使用。 this is my service, 这是我的服务,

 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);
   }
 }

in my function i send value to this service, 在我的职责中,我向这项服务传递价值,

 this.pService.template_type('one');

and in another funtion in the same component i call this service to get value 在同一个组件的另一个功能中,我称此服务以获取价值

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

but it return 'hi' first,, after the function call it return the value..but i need value in first...any wrong in my code ? 但是它首先返回“ hi”,在函数调用后返回值..但是我首先需要值...代码中是否有错误?

It sounds like you don't want to use a BehaviorSubject , but instead a ReplaySubject(1) : 听起来您不想使用BehaviorSubject ,而是要使用ReplaySubject(1)

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

This doesn't have an initial value. 没有初始值。

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

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