Exploring RxJS and Observables is a new journey for me. I recently came across this informative tutorial ->
I have a question:
There are three components involved:
OnePage: manipulates and displays the answers
Service: manages the answers
SecondPage: also deals with the answers
In the provided link, data subscription to component is demonstrated like this
ngOnInit() { todosService.todos$.subscribe(updatedTodos => this.componentTodos = updatedTodos); todosService.loadTodos(); }
And in my case, it looks something like this
onPageWillEnter(){ this.service.answers$.subscribe(updatedAnswers => { this.answers = updatedAnswers; console.log("we subscribed from questions"); }); this.service.load().then((rootobject:RootObject) =>{ this.rootobject = rootobject; this.questions = rootobject.Item.questions; this.current_question = this.service.current_question; this.pushNextImage(0); console.log(this.answers, " Questions page loaded => then"); }); console.log(this.answers, " Questions page loaded"); }
So far so good. Updating both Global "answers" and local "answers" works perfectly fine.
markQuestion(event){ this.current_question = this.questions[event.q_number]; this.current_question_number = event.q_number; //Mark the answer in answers this.answers[event.q_number-1] = event.val; this.service._answersObserver.next(this.answers); }
However, when checking the "service.answers" after updating, everything seems up-to-date BUT.
When moving to the SECOND PAGE:
onPageWillEnter(){
this.service.answers$.subscribe(updatedAnswers => {
this.answers = updatedAnswers;
console.log("we subscribed from questions");
});
//this.service._answersObserver.next(this.service.answers);
console.log(this.service.answers$);
console.log(this.service.answers," Page loaded AnswerSheet" , this.answers ," => answer_list");
}
The subscribe event doesn't trigger at all. Nothing appears in the console..unless I do this:
this.service._answersObserver.next(this.service.answers);
Why does this happen?
If you want to check out the plunker for more details, here is the link https://plnkr.co/edit/c3fu5hsPZXslLegdeD0p?p=info