简体   繁体   中英

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 ?

It sounds like you don't want to use a BehaviorSubject , but instead a ReplaySubject(1) :

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

This doesn't have an initial value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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