Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

rxjs - Angular get observable value in other component

what i want to achieve:

I have two components that are not linked

  • I want to set a variable's value from component1 and then use it in component2
  • Component2 should get updated value if its changed in component1

My solution:

  • Inject a service in both the components
  • add an observable in that service
  • set observable value from component1 and subscribe in component2

Problem in above solution: The subscribe in component2 is not called when component1 value is updated, its only called at page loading.

Please see the code below:

service

export class HomeService {
  public receiveMedOrderVisibleSubject: BehaviorSubject<any>;
  public receiveMedOrderVisibleObservable: Observable<any>;

  constructor() {
    this.receiveMedOrderVisibleSubject = new BehaviorSubject<any>(
      localStorage.getItem("RECEIVED_MED_ORDERS_COUNT")
    );
    this.receiveMedOrderVisibleObservable = this.receiveMedOrderVisibleSubject.asObservable();

    this.receiveMedOrderVisibleSubject.subscribe(data => {
      console.log("HomeService subscriber called" + data);
    });
  }
}

Component1

export class HomeComponent implements OnInit {
  constructor(private homeService: HomeService) {}

  ngOnInit() {
    this.homeService.receiveMedOrderVisibleSubject.next(1);
  }

  setData() {
    //endpoint will return the data that should be set in variable, and that endpoint is called when dropdown value is changed.
    //I have removed that code for simplification
    this.homeService.receiveMedOrderVisibleSubject.next(10);
  }
}

component2

export class PageOneComponent implements OnInit {
  constructor(private homeService: HomeService) {}

  ngOnInit() {
    this.homeService.receiveMedOrderVisibleSubject.subscribe(data => {
      console.log("page-one subscriber called" + data);
      //this is called only when page is loaded, it's not called when this.homeService.receiveMedOrderVisibleSubject.next(10); is executed from component1
    });
  }
}

How can I set the value in component1 and then use it in component2 when both components are not internally linked, you can say that component1 is header and component2 is loaded by active URL


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...