如何访问行为主体之外的订阅行为块的变量 [英] how to access variable of subscribe block of behaviour subject outside the block

查看:57
本文介绍了如何访问行为主体之外的订阅行为块的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用行为主题,并将其订阅到ts文件中.

I am using behaviour subject and subscribe it in ts file.

试图访问ts文件中主题块之外的变量.

trying to access the variable outside the subject block in ts file..

service.ts的代码

code for service.ts


 private messageSource = new BehaviorSubject<any>(null);

  constructor(
    private apiService: ApiService
  ) {
  }

  // try

  sendMessage(value: any) {
   this.messageSource.next(value);
  }

  get getMessage() {
    return this.messageSource.asObservable();
    
   }```

now in TS file

ngOnInit(){

ngOnInit() {

//this.viewUser = this.commonService.getMessage;

// this.viewUser = this.commonService.getMessage;

this.subscription = this.commonService.getMessage.subscribe(value => {
  this.viewUser = value; 
  console.log(this.viewUser)
 });


 console.log(this.viewUser)

}

文件控制台显示数据.但是在第二个控制台中,它显示行为主体的初始值,即.无效的我如何获取块外的数据

file console showing data.. but in second console , it is showing inital value of behaviour subject ie. null how can i get data outside the block

推荐答案

使用

The simplest way to share data between sibling components by using TypeScript Setter and Getter instead of an Observable (which we must need to unsubscribe to prevent memory leak).

service.ts

  _message: string;

  set message(value: any) {
    this._message = value;
  }

  get message() {
    return this._message;
  }

通过任何组件或服务等设置值

Set value from any component or service etc

this.commonService.message = 'some message'; 

最后无需订阅等即可获得价值

And finally get the value without any subscription etc

ngOnInit() {
 this.viewUser = this.commonService.message
 console.log(this.viewUser);
}

这篇关于如何访问行为主体之外的订阅行为块的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆