Observation - Various Parties Subscribing

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

Answer №1

Is it possible to achieve the same functionality by including this.service.answers$.subscribe in the constructor of the AnswerSheetPage class rather than the onPageWillEnter method?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The attributes of an Angular directive may be present but not officially set until the setTimeout function with 0 seconds is called

Check out this link angular.module('mainApp', []) .directive('list', function customFactory() { return { restrict: 'E', scope: { size: '=', listWid ...

Issue with Angular dynamic style not functioning properly in Chrome

I am looking to increment the height of a div by 20px gradually. Why does the code below only function properly in Chrome and not in IE? <div ng-repeat="p in percentage"> <div style="height: {{$index*20+5}}px"></div> </div> ...

Utilize Firebase Realtime Database to generate new data entries using triggers

Hey there, to all the amazing folks at stackoverflow who have been supporting me over the years, I have a new question for you! I've been delving into Android programming for quite some time now and I enjoy exploring different ways to optimize apps. ...

Linking a variable in typescript to a translation service

I am attempting to bind a TypeScript variable to the translate service in a similar way as binding in HTML markup, which is functioning correctly. Here's what I have attempted so far: ngOnInit() { this.customTranslateService.get("mainLayout.user ...

Definition of Typescript:Named Function Expression (NFE)

In my current project, I am examining the JS code snippet below as part of creating a .d.ts file: BatchBuffer.js var Buffer = function(size) { this.vertices = new ArrayBuffer(size); /** * View on the vertices as a Float32Array for posi ...

What are the steps to set up tsline in settings.json file?

Currently utilizing visual studio code Upon searching for the settings.json file, the contents appear as follows: { "liveServer.settings.donotVerifyTags": true, "liveServer.settings.donotShowInfoMsg": true, "javascript ...

A guide on accessing URL query parameters using AngularJS

Is it possible to extract specific URL parameters using AngularJS and then assign their values to textboxes? For instance, a sample URL would be: http://example.com/?param1=value1 I've come across examples involving $location, routing, and services ...

What are the best practices for establishing a secure SignalR client connection?

While tackling this issue may not be solely related to SignalR, it's more about approaching it in the most efficient way. In C#, creating a singleton of a shared object is achievable by making it static and utilizing a lock to prevent multiple threads ...

Detecting clicks outside of a component and updating its state using Typescript in SolidJS

Hi there, I am currently learning the SolidJS framework and encountering an issue. I am trying to change the state of an element using directives, but for some reason it is not working. Can anyone point out what I might be doing wrong? You can find the ful ...

Get rid of the unnecessary vertical line that is located at the end of the string

I have come across a situation similar to the one demonstrated in this code snippet: http://plnkr.co/edit/eBjenGqgo3nbnmQ7XxF1?p=preview Currently, I am working with AngularJS 1.5.7. The directives used in my input - ( first ) textarea are the same as tho ...

Object data is not being received by the defaultValue in React Hook Form

I am currently utilizing React Hook Form to facilitate the process of editing/updating data. I retrieve my data from zustand with a value type of any, and then proceed to save it as the defaultValue in React Hook Form. However, when attempting to acquire v ...

Creating a form with required fields in Angular and using the ngIf directive

Update: modified the sample code to incorporate TypeScript for better clarity I have a form with various buttons for users to choose from. The submit button is initially disabled until a user selects a button. However, there's a unique requirement wh ...

Is there a way to reset useQuery cache from a different component?

I am facing an issue with my parent component attempting to invalidate the query cache of a child component: const Child = () => { const { data } = useQuery('queryKey', () => fetch('something')) return <Text>{data}& ...

Dealing with Angular errors: How to handle a 404 page not found situation

I am retrieving data from a JSON file by making an HTTP request. Once I subscribe to the data, I read the JSON content. In this scenario, my goal is to verify whether the path is incorrect and if so, return a 404 error message. getMapConfig(): Observable&l ...

Jest Test - Uncaught TypeError: Unable to create range using document.createRange

my unique test import VueI18n from 'vue-i18n' import Vuex from "vuex" import iView from 'view-design' import {mount,createLocalVue} from '@vue/test-utils' // @ts-ignore import FormAccountName from '@/views/forms/FormAcco ...

The data for my registration is not getting stored in the Firebase database as expected

I'm currently working on a registration app and it's my first time using firebase. My email address is successfully stored in the authentication section of firebase. However, when I try to connect my app to the database to store additional infor ...

What is the best way to add a header field to a response using NestJS?

I am attempting to create a login function in my code, but encountering an issue: @Post('login') async login(@Body() body: AuthDto, @Res() res: Response) { const loginResponse = await this.authService.login(body); console ...

Utilizing AngularJS to invoke an ng-controller within a nested controller structure

Take a look at this sample code from the cshtml file: <div> <button type="button" ng-click="recalcButton()">Recalc Button</button> </div> <div ng-controller="appealPartialController"> < ...

Implement a delay for a specific function and try again if the delay expires

In my TypeScript code, I am utilizing two fetch calls - one to retrieve an access token and the other to make the actual API call. I am looking to implement a 1-second timeout for the second API call. In the event of a timeout, a retry should be attempted ...

Encountering a 401 error while trying to access a protected endpoint on AWS Cognito

Currently, I am dealing with a Cognito user pool that has an application integration for JavaScript lacking a secret key. Interestingly, I can successfully log in using the code snippet below: private static async signin(role: UserRole): Promise<strin ...