Observable subscription does not result in updating the value

One of the challenges I'm currently facing in my Angular application is the synchronization of data from a server. To keep track of when the last synchronization took place, I have implemented a function to retrieve this information:

fetchLastSyncDate(): Observable<Date> {
    return this.ormService.manager$.pipe(
      switchMap(manager => manager.find(OfflineStatusEntity)),
      map(statusArr => statusArr[0]!.lastSync || new Date(0))
    );
  }

The actual synchronization process is initiated by the following function:

synchronizeData(): Observable<void> {
    const syncDate = new Date();
    return this.fetchLastSyncDate().pipe(
      switchMap(modifiedAfter =>
        this.httpClient.get<SynchronizationDto>(
          `${this.baseUrl}/${DateTime.fromJSDate(modifiedAfter).toISO()}`
        )
      ),
      switchMap(data => from(this.updateDataFromServer(data, syncDate)))
    );
  }

To update the synchronization date after a successful synchronization, I've included the following method:

private async updateDataFromServer(
    data: SynchronizationDto,
    syncStart: Date
  ): Promise<void> {
    ...
     // save sync date
    const manager = (await firstValueFrom(this.ormService.dataSource$)).manager;
    const status = (await manager.find(OfflineStatusEntity))[0]!;
    status.lastSync = syncStart;
    await manager.save(status);
}

For real-time display of the last synchronization time in the UI, I have integrated the subscription logic as shown below:

export class MyComponent implements OnInit {
    subscription = new Subscription();
    lastSyncTime: string | null = null;

    ngOnInit(): void {
      this.subscription.add(
        this.synchronzationDataService.fetchLastSyncDate().subscribe(newSyncDate => {
          this.lastSyncTime = newSyncDate.toLocaleString('de-CH');
          this.changeDetectorRef.markForCheck();
        })
      );
    }
}

Although the initial load correctly displays the latest sync time, I encounter an issue where the lastSyncTime value does not update after running a synchronization task. Any guidance on what could be missing would be greatly appreciated.

As I navigate through the realm of observables, I find myself questioning whether my understanding of subscriptions aligns with the intended behavior. Shouldn't subscribing to an observable function automatically trigger the subscription upon any changes in the observable's value?

Answer №1

Observables represent data streams evolving over time. They have the ability to notify data, handle errors, and complete their stream of data. Once an Observable completes, it can no longer notify any additional data.

  • notify data
  • error
  • complete Once complete an Observable can not notify any more.

HTTP calls are a specific type of Observables that notify data just once upon receiving a response, and then either complete successfully or result in an error if something goes wrong. Mapping HTTP calls as Observables makes sense because they asynchronously provide results, embodying the concept of "a stream of data over time."

When HTTP calls are mapped as Observables, they are triggered upon subscription. In your scenario, where subscription takes place in the ngOnInit method, you essentially get the timestamp representing "the time when you first open the app."

If you want to obtain the correct time again, you need to execute the following code:

this.synchronzationDataService.fetchLastSyncDate().subscribe(newSyncDate => {
    this.lastSyncTime = newSyncDate.toLocaleString('de-CH');
    this.changeDetectorRef.markForCheck();
}

It appears that when you mention "running the synchronization" again, you may be referring to subscribing to the Observable returned by synchronizeData(). However, this alone would not replicate the functionality present in the ngOnInit 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

Issue with undefined arrays in the Angular merge sort visualization tool

I am currently working on developing a visualizer for sorting algorithms using Angular. However, I have encountered some difficulties while implementing merge sort. As a Java programmer, I suspect that there may be an issue with my TypeScript code and the ...

Exploring the world of TypeScript type mappings

I'm currently working on enhancing a function with type annotations. This particular function takes an array of typed objects as parameters and returns a mapped array of a different type: const createAnimals = <T extends AnimalFactory<any>[]& ...

What could be preventing my state from changing to false when I click the close button on the menu?

Despite initializing my state to false, the problem arises when I open and close my menu. The state never actually becomes false, causing the closing animation of the NavBar to not run as expected. The component: import CloseButton from "./CloseButto ...

Tips for verifying the presence of an active session after closing the browser

Here is my situation: When a user logs into the app and then opens another browser window, they are already authenticated thanks to express-session, bypassing the login page. This pattern continues for subsequent browser windows. The issue I am facing no ...

Angular 2 is throwing an error: Unhandled Promise rejection because it cannot find a provider for AuthService. This error is occurring

My application utilizes an AuthService and an AuthGuard to manage user authentication and route guarding. The AuthService is used in both the AuthGuard and a LoginComponent, while the AuthGuard guards routes using CanActivate. However, upon running the app ...

retrieve data from URL parameters (navigation backward)

When navigating from the main page to the transaction page and then to the details page, I have implemented a go back feature on the details page. Using the state, I pass data when navigating back so that I can access it again from the transaction page. H ...

Angular displays the error message TS2339, stating that the property 'handleError' is not found on the 'HeroService' type

Hey everyone, I know there are already a few questions out there about Typescript compilation errors, but I'm facing a unique challenge that I can't quite figure out. I'm currently working on the Angular Tour of Heroes app and trying to com ...

Is it possible to run NestJS commands without relying on npx?

I recently installed nestjs using npm, but I encountered an issue where it would not work unless I added npx before every nest command. For example: npx nest -v Without using npx, the commands would not execute properly. In addition, I also faced errors ...

What are some effective ways to exclude multiple spec files in playwright?

Within my configuration, I have three distinct projects. One project is responsible for running tests for a specific account type using one login, while another project runs tests for a different login. Recently, I added a third project that needs to run t ...

What steps should be followed in order to generate a child or item with no assigned key

Here is my TypeScript code designed to automatically record the time of data creation: import * as functions from 'firebase-functions'; export const onAccCreate = functions.database .ref('/Agent/{AgentID}') .onCreate((snapshot, contex ...

Visual Studio is refusing to highlight my code properly, intellisense is failing to provide suggestions, and essential functions like go to definition are not functioning as expected

Due to a non-disclosure agreement, I am unable to share any code. However, I am experiencing an issue with Visual Studio not highlighting my code or allowing me to utilize its built-in tools. While I can rebuild the project, I cannot edit or access any fil ...

ng2-dragula error: issues with setting options and dropping version

It seems that version 1.5.0 supports this.dragulaService.setOptions, while version 2.1.1 does not, and vice versa with this.dragulaService.drop subscribe where version 2.1.1 supports it but 1.5.0 does not. Check out the Stackblitz Fork for version 1.5.0 ...

What steps should I follow to ensure that the processData function waits for the data returned by the getData function in Angular?

After calling the getData function, each object is stored in an array and returned. Now I need the processData function to await these results from getData and then further process them. However, when I try to console.log(cleaningData), I don't see an ...

Using FormControl Inheritance in Angular 4

My goal is to enhance the functionality of a FormControl by creating a subclass with additional properties. These properties will then be utilized in custom form controls to modify behavior. I attempted to inherit from FormControl (let's call it Stan ...

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

Discover the location of items within an array

Currently, I am working with a JSON object that has the following structure. My objective is to determine the index based on ID in order to retrieve the associated value. The indexOf function appears to be suitable for arrays containing single values, but ...

What is the method to acquire the firestore reference type in TypeScript?

Here is the code I am working with: import { DocumentReference } from '@firebase/firestore-types' export type Recipe = { author: string title: string ingredients: { quantity: number ingredient: DocumentReference["path"] ...

How can you verify the data type of an object without resorting to type guarding

I have a situation where I need to deal with different types of objects. export interface A { links: number name: string } export interface B { cat: boolean name: string } Initially, I considered using this method: const IsTypeB = (obj: any): obj ...

Angular displays an error message and applies an invalid class when a form is submitted

I have created a form in Angular(5) using a template-driven approach. My goal is to display error messages and apply different styles to the input fields when they are invalid, especially when the form is submitted. Currently, I am able to achieve this fu ...

Creating a responsive class getter with Vue.js 3 using the Composition API: a guide

How can I set up a class instance property to reactively display an error message when authentication fails? UserModel.ts export class User { private error: string; set errorMessage(errorMessage: string) { this.error = errorMessage; } get err ...