Monitoring controller variables in Angular 4

Imagine having a piece of old code that you don't want to modify. There are three server calls involved in fetching data, and after all three methods succeed, you need to execute some additional code. I introduced a variable and now want to monitor it for changes (ngOnChanges is not an option).

Take a look at the following code snippet:

ngOnInit() {
  this.loadedReq = 0; // This variable will reach 3 when all requests are successful, triggering custom code execution. How do I watch this variable?

  this.getCars();
  this.getModels();
  this.getTypes();
}

getCars() {
  return this.myService.getCars(this.clientId)
    .subscribe((response) => {
      this.loadedReq++;
    });
}

getModels() {
  return this.myService.getModels(this.clientId)
    .subscribe((response) => {
      this.loadedReq++;
    });
}

getTypes() {
  return this.myService.getTypes(this.clientId)
    .subscribe((response) => {
      this.loadedReq++;
    });
}

someMethodWhenAllLoaded(){}

Is there a way to achieve this without altering the methods extensively (e.g., implementing complex RxJs logic on responses)?

If not, how can a workaround be created in this scenario?

Answer №1

There are various methods to accomplish this task, one approach is to utilize the .zip() operator in RxJs to synchronize the completion of multiple tasks.

We're also storing a reference to it so that we can unsubscribe onDestroy.

zippedSubs$: Subscription;

  ngOnInit() {
    this.zippedSubs$ = Observable.zip([
      this.getCars(),
      this.getModels(),
      this.getTypes()
    ]).subscribe(result => {
      console.log('All processes completed successfully!');
    });
  }

  ngOnDestroy() {
    this.zippedSubs$.unsubscribe();
  }

  getCars() {
    return this.myService.getCars(this.clientId);
  }

  getModels() {
    return this.myService.getModels(this.clientId);
  }

  getTypes() {
    return this.myService.getTypes(this.clientId);
  }

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

Efficiently handle the data to prevent unnecessary API requests

In my Angular application (v11), I am utilizing a service to retrieve data from the backend. My goal is to make the API call only once and then update the data, specifically the title. The issue I am facing is that every time I change the title, the creat ...

Uncertain about where and how to properly register a service in Angular 2

All: Today was my first day diving into Angular2, as I embarked on the official TUTORIAL at part 6: Routing Around the App https://angular.io/docs/ts/latest/tutorial/toh-pt5.html Within the Create AppComponent section, it is mentioned: Add HeroService ...

Creating Dynamic Templates in Angular 6

We are currently rendering the template dynamically in our application by utilizing AngularJS's $compile to compile HTML on the fly. I am wondering if there is a similar feature in Angular 6 that allows us to manually compile HTML. I have searched for ...

Issue: Unable to locate control with the specified name

Having trouble submitting a reactive form with form arrays, I've searched through various solutions on different forums without success. It seems like I may be overlooking something obvious. The errors I'm encountering are "ERROR Error: Cannot fi ...

Merge two observables together to create a single observable that emits values from both sources. Only one observable will emit values

I am looking to combine two observables of type T[] obtained from httpservice. I have tried using forkJoin and zip, but they both return an Observable of type [T[], T[]]. However, I want to receive an object of type T[] as shown in the following code snip ...

Preventing runtime error in Next.js API routes by handling axios exceptions

I am currently working on creating an API route in Next.js that sends a request to my backend and saves the token in the cookies. However, I am facing an issue where 4xx responses are causing an Unhandled runtime error. Despite everything working correctly ...

Configuring Angular routes based on service method invocation

I have my routes configured in @NgModule. I also have a service that determines which parts of the application to display based on specific conditions. I need to call this service and adjust the routes according to its output. Issue: The route configurati ...

Encountering the error message "Unable to connect to this site" while attempting to run Angular 8 using Docker Compose

After successfully running npm start for my angular UI application, I encountered an issue when moving API and UI into docker. Every time I tried to access the site, it displayed "This site can’t be reached". Can someone please assist me in identifying w ...

Automated Integration with Visual Studio Team Services: Empowering ASP.NET Core and Angular 4 Collaboration

I am currently working on an ASP.NET Core web app using Visual Studio 2017, and I am developing an Angular 4 front-end project in Visual Studio Code. The goal is for the Angular 4 project to be integrated with the Core web app, and I need to set up continu ...

When working in Visual Studio Code, it is important to note that [js] types are limited to usage within

Can .js files be used in a TypeScript project in VS Code? I recently cloned a React Native project from a GitHub repository and opened it in Visual Studio Code. However, when I added a tsconfig.json file to start using TypeScript, I encountered a lengthy l ...

Problem with jHipster image display

I'm facing an issue while trying to load an image using Angular. The source of the image should come from an attribute of an object within an *ngFor loop, like this: <div *ngFor="let object of objects"> <img src="{{object.imagePath}}"> ...

Identify duplicate value assignments for a property using ngOnChanges

Essentially, I am working with an array of objects and my goal is to pass the index of a selected object from the array to another component using @Input. The issue arises when I try to select the same item twice because the ngOnChanges function does not ...

Unable to access property value following AJAX call

Here is my code snippet: constructor(props: any) { super(props); this.state = { list: [], }; } public componentWillMount() { this.loadData(); } public loadData = () => { axios.get(someURL) .then((response) = ...

What is the reason behind TypeScript classifying the argument type from the function as 'never'?

Presented here is the combined type of two signatures for the filter function and the function itself. type Filter = { (arr: string[], f: (item: string) => boolean): string[] (arr: number[], f: (item: number) => boolean): number[] } let filter: ...

TS object encountering a restriction with an inaccessible method

I'm facing a challenge trying to utilize a method stored on a Typescript class within a Vue component. When I attempt to use a method defined on that class from another class (which also happens to be a Typescript Vue component), the console throws a ...

Errors are being encountered with Angular 15 despite it being expected to offer support for typescript 4.9.3

I'm currently working on updating my project to utilize TypeScript 4.9.3, and the newest version of Angular (@15) is said to be compatible with it (https://angular.io/guide/update-to-version-15) However, no matter what steps I take, I keep encounteri ...

Sharing data between components in Angular 2 using the <router-outlet> technique

Having just started exploring Angular 2, I am eager to pass a boolean value from one component to another using <router-outlet> After some research, it seems like the best approach is to utilize a service. My aim is to toggle a boolean variable in ...

Verifying whether the filter query will produce any matches

I'm currently working with a *ngIf statement and I need to show a specific message when the condition is not met. However, I'm facing difficulties in finding a way to achieve the opposite of the filtered result. Essentially, I want to display a m ...

Tips for updating an observable in Angular 6 following a POST request

One of the challenges I am facing is related to the table displaying ticket information. Users have the ability to add new tickets and send them to the backend. However, the issue arises when the table does not update automatically with the newly added tic ...

Can data be filtered based on type definitions using Runtime APIs and TypeDefs?

My theory: Is it feasible to generate a guard from TypeDefs that will be present at runtime? I recall hearing that this is achievable with TS4+. Essentially, two issues; one potentially resolvable: If your API (which you can't control) provides no ...