Resetting a Subject entity

Is there a way to reset an Observable object? I'm not sure if "reinitialize" is the right term, but essentially what I want is to update the data without creating a new Observable object or new subscriptions.

  1. I want existing subscriptions to seamlessly continue working
@Injectable({
  providedIn: 'root',
})
export class MyService {
  private url = 'http://mydummydomain.com/api/entries';
  private data$: Observable<any>;

  constructor(private http: HttpClient) {
    this.data$ = this.http.get(this.url).pipe(
      shareReplay(1)
    );
  }

  getData(): Observable<any> {
    return this.data$;
  }
  
  reloadData() {
    // TODO:
    // Refresh data from the url
    // This should be a function without any input parameters or return value
  }
}

Appreciate any help on this matter.

Answer №1

give this a shot

updateData$ = new Subject<void>();
info$ = this.updateData$.pipe(startWith(null), switchMap(() => this.http.get(this.url)), shareReplay(1));


refreshInfo() {
  updateData$.next();
}

Answer №2

Consider using BehaviorSubject to solve your issue without creating a new observable. However, I recommend utilizing ngrx or mobx for data manipulation as it is more convenient. I find it unusual that you have set the data as private and created a getter function; typically, variables in a view are declared as public.

@Injectable({
  providedIn: 'root',
})
export class MyService {
  private url = 'http://mydummydomain.com/api/entries';
  public data$: BehaviorSubject<any> = new BehaviorSubject(null);

  constructor(private http: HttpClient) {
    this.http.get(this.url).pipe(
      take(1)
    ).subscribe((data) => {
      this.data$.next(data);
    });
  }
  
  reloadData() {
    this.http.get(this.url).pipe(
      take(1)
    ).subscribe((data) => {
      this.data$.next(data);
    });
  }
}

It's advisable to centralize your API logic within the service so that the data can be shared across multiple components efficiently when stored in one place.

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

Ways to obtain a data type as an element in an array?

const ratingList = {1: "", 2: "", 3: "", 4: "", 5: ""} type ratingType = keyof typeof ratingList ...... {Object.keys(ratingList).map((value, index) => { if (parseInt(value) <= rating) re ...

Express server for an Angular 2 application failing to handle API requests

My angular2 application is currently hosted on Heroku using a Node/Express server. For example, when the app makes an API call to retrieve posts at appurl.com/posts, it is structured as appurl.com/api/posts. All API calls are made at appurl.com/api/~wha ...

Nodemailer fails to display an error message when the email is not successfully sent

I am currently working on implementing nodemailer for sending emails. However, I noticed that if the email address in the "to" field is incorrect, the email is not sent as expected. The issue is that there is no error displayed and the function still resol ...

Customizing CSS for tables within a mat-menu in Angular Material

I am currently developing an application using Angular 7 and Angular Material cdk 6. This is my first experience working with Angular Material and I am facing a challenge in overriding the CSS styles of my columns. Despite several attempts, none of them se ...

Continuing the process of uploading the file

In my development of a single page application that allows users to upload photos, I have encountered a dilemma. What happens if a user is uploading multiple photos and then closes the browser? When they log back in, I want the browser to automatically c ...

Error Alert: Cannot access navigator in Angular Universal platform

I utilized the official angular-cli guide to incorporate angular-universal into my existing angular-cli application. Successfully implemented server-side rendering for my angular-cli app. However, upon attempting to integrate ngx-leaflet, I encountered th ...

Passing data between two distinct components when a button is clicked within Angular 4, all while ensuring the route URL remains unchanged

Having recently started working with Angular 4, I encountered an issue when trying to pass data from one component to another without using ActivatedRoute to send the data via the URL. In my searchOption.component.html file, the Submit button code looks l ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

Separate the business logic from the HTML code in Angular to prevent repetition and make the code

I have a lengthy HTML code with ngSwitch for 3 cases and 4 small cases within the default case, all using the same icon structure. How can I shorten my HTML code and eliminate business logic from it? The hierarchy to display different icons is: Servicefl ...

Error: Spy creation was anticipated to have been invoked

Currently, I am in the process of writing unit test cases for an Angular 7 Component that utilizes an async service. Unfortunately, I encountered the following error: Error: Expected spy create to have been called once. It was called 0 times. Below is t ...

Angular routing displays a 404 error message indicating that the page cannot be found

After implementing Angular routing, I encountered a frustrating 404 error when accessing certain routes. Strangely enough, everything works perfectly fine when testing on localhost: https://i.sstatic.net/1zwfF.png However, once I tried to access the ap ...

The module node_modules/angular-2-local-storage/dist/index.d.ts is encountering a Metadata version mismatch error. The current version found is 4, however, the expected version

I encountered an error while using the Angular2 application and running the command npm start. Here is the full error message: ERROR in Metadata version mismatch for module /home/x/Desktop/koohbaad-web/node_modules/angular-2-local-storage/dist/index.d.ts ...

Guide on importing a custom CSS file from Syncfusion Theme Studio into an Angular project

Is there a way to incorporate custom scss files downloaded from Syncfusion Theme Studio into Angular CLI without adding the URL to the styles section in angular.json? Can we directly import it into styles.scss instead? I attempted to do so by including th ...

What is the rationale behind TypeScript permitting undefined methods?

Currently, I am working on a presentation for my development team about TypeScript. I want to demonstrate the importance of type checking through examples, but I'm stumped as to why this particular piece of code is not throwing a compile-time error wh ...

Why does my Visual Studio Code always display "building" when I launch an extension?

https://code.visualstudio.com/api/get-started/your-first-extension I followed a tutorial to create a hello world extension. Why does my VSCode always display 'building' when I run the extension? Executing task: npm run watch < [email p ...

What could be causing the media queries to not take effect at a max-width of 425px?

When I try to apply media queries for max-width 768px and max-width 425px, I noticed that the styles intended for max-width 768px are also being applied when the width is 425px. This results in the al-articles-tags-chip-list-container having a width of 600 ...

Unable to retrieve nested objects from HTTP Response

After receiving data from a HTTP Response, I am trying to access and display it in my template. However, despite storing the data into a component variable, I am encountering issues when trying to access specific properties of the object. { "files": [ ], ...

Components in Angular modules that are loaded lazily with identical names

I have developed an Angular application with multiple lazy-loaded modules. Each of these modules contains different components that are conceptually similar but vary in content. For example, each module may have its own "home" component. Is it advisable t ...

Ensuring that Http requests are carried out upon opening Angular-PWA

Whenever my Progressive Web App is opened, I want to send an HTTP request. It works perfectly when the user closes the app, but if it remains in memory and stays open (for example, until the next day), then my HTTP request doesn't get executed. The c ...

Tips for creating a unit test case for a specialized validator in angular reactive forms

Looking for guidance on creating a test case for this specific method: export class CustomErrorStateMatcher implements ErrorStatematcher { isErrorState(control: FormControl,form:NgForm | FormGroupDirective | null){ return control && control.inval ...