Unable to successfully process HTTP Request Unsubscribe commands

When working with my component, I am retrieving data from a JSON file through services and subscribing to it. There is a condition check in place to stop the subscription once a specific criteria is met, but unfortunately, it doesn't seem to be working as expected.

Service

getUserData() {
     const url = './assets/json/userslist.json';
     return this.http.get(url);
}

Component

const subscription = this.getuser.getUserData().subscribe(data => {
  Object.values(data).forEach((userdetail) => {
    // tslint:disable-next-line:max-line-length
    if (userdetail.username.indexOf(form.value.email) !== -1 && userdetail.password == form.value.password) {
      console.log('asd');
      if (userdetail.active == true) {
        console.log('asasdfasd');
        this.EventEmitterObj.emit(form.value.email);
        this.router.navigateByUrl('/home');
      } else if (userdetail.active == false) {
        console.log('asd23423432');
        this.deactivateAlert = 'The account is deactivated';
      }
      subscription.unsubscribe();
      console.log('issue');
    } else {
      console.log('12341243');
      this.deactivateAlert = 'Incorrect Username/Password';
    }
  });
});

Answer №1

Angular HTTPClient

The angular HTTPClient automatically handles unsubscribing upon request completion, whether successful or on error.

By the time you initiate an unsubscribe action, the http request has already received a success response and is considered completed.

It seems like you might be expecting the unsubscribe action to halt your loop. Remember, unsubscribing a Subscription does not stop a foreach loop. To end the foreach loop, simply use return or break.

Answer №2

Make sure to place your unsubscribe action outside of the subscribe call. This way, the subscribe call will only execute after receiving a response from the server.

If you need to cancel a subscription request, be sure to do so separately.

For ending a foreach loop, you can use the return keyword.

Please feel free to ask for any additional clarification if needed.

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

Having issues with an Angular reactive form that includes a custom form-level validator and the 'blur' updateOn option?

Having issues combining the following: angular reactive form custom validator at form level (cross-field validator) usage of the 'updateOn' option set to 'blur' A demonstration of the problem can be found in this simple stackblitz: h ...

Issue with Angular application failing to fetch data from JSON server

I've been attempting to retrieve data from a local server, but so far I'm not getting any results. The concept is to have a service handle the retrieval process and return an observable for any components in need of the data to subscribe to. dis ...

Is it possible for me to dynamically alter the innerHTML of an input element using

I am working on a small Angular application. One of my components uses innerHTML to display content. <div [innerHTML]="serviceShared.currentMood"></div> However, when I change the value of serviceShared.currentMood in the main component, noth ...

Issue with Nestjs validate function in conjunction with JWT authentication

I am currently implementing jwt in nest by following this guide Everything seems to be working fine, except for the validate function in jwt.strategy.ts This is the code from my jwt.strategy.ts file: import { Injectable, UnauthorizedException } from &ap ...

Avoid insecurely assigning an any value in TypeScript

Take a look at this code snippet: const defaultState = () => { return { profile: { id: '', displayName: '', givenName: '', }, photo: '', } } const state = reactive(defaultState() ...

What is the best way to mock an internal function within my route using sinon?

Currently, I have my own internal function defined in the greatRoute.ts file: //in greatRoute.ts async function _secretString(param: string): Promise<string> { ... } router .route('/foo/bar/:secret') .get( async (...) => { ...

Assistance required in configuring eslint for a monorepo with Yarn 3 and TypeScript

I've been struggling to configure ESlint in my monorepo while using Yarn 3.2.4 as the package manager. To see an example project, check out this GitHub repository. Here is the structure of the project: /monorepo ├── /configs │ ├── /esl ...

Ways to increase the size of a div to match the maximum height of its parent container

My current project involves using an angular dialog layout where the API to open and manage the dialog comes from a separate library. The dialog's parent container has a max-height attribute, meaning the dialog's height is determined by its conte ...

Similar to [JsonPropertyName] in C#, but for TypeScript

Need help deserializing JSON response into a class defined in Angular. Let's use the example class below: export class ChatHubInfo { hubUrl: string = undefined! accessToken: string = undefined! } However, the JSON response is structured different ...

Attempting to intercept a 401 error in an HTTP interceptor, I aim to refresh my session and then retry the initial request

My goal is to intercept responses returning from the /api, catching them if they are a 401 error, executing a refresh session action, and then retrying the original HTTP call again (while also preventing it from infinitely looping if another 401 error occu ...

What is the best way to bring a module into an Angular project?

I have a project in Angular with an additional module created as an npm package. The structure of the module is as follows: --otherModule --other-module.module.ts --index.ts --package.json index.ts: export { OtherModule } from './other-module ...

Developing web applications with Angular 6, C#, and MVC involves dynamically generating and returning JsonResults from the controller in the form of

I have been working on exporting datasets to Excel within an Angular 6 application. To achieve this, I have been utilizing XLSX and File-save functionalities as outlined in the following example: https://medium.com/@madhavmahesh/exporting-an-excel-file-in- ...

Angular2, where elements glide in from the left with a smooth animation

I'm currently developing a progress bar feature that slides in from the left side. My current implementation sets the width of the bar to 40%, but I want to make it dynamic by taking an input for the desired percentage. animations: [ trigger(&ap ...

How can we effectively map Typescript Enums using their keys without relying on a Map?

Consider the following Enum instances: export enum TopicCategories { GUIDES = 'Guides', TASKS = 'Tasks', CONCEPTS = 'Concepts', FORMULAS = 'Formulas', BLOGS = 'Blogs' } export enum Top ...

I encountered an eslint error when I was trying to configure Vue 3 + Quasar with a Firebase config.ts file. The error stated that there was an unsafe assignment of an `

Recently, I set up a new Vue 3 project with Quasar using the Quasar CLI. In order to store my firebase configuration, I created a new file called src/firebase/config.ts, which looks like this: // Import necessary functions from SDKs import { initializeApp ...

I am constantly facing the same frustrating error in every meanstack project I work on: Failed to load resource: net::ERR_CONNECTION_REFUSED. Can't seem

I've been diving into educational resources to learn how to build meanstack applications with basic CRUD capabilities. After downloading various projects from Github and setting up the necessary modules, I encounter a consistent error when running the ...

What is the best way to retrieve the names of "string" properties from an interface in TypeScript?

Explore Typescript playground I aim to extract the string characteristics from SOME_OBJECT and form them into a union type. Thus, I anticipate STRING_KEYS to signify "title" | "label" interface SOME_OBJECT { title: string, ...

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...

Angular: Exploring the most effective strategies for optimizing code within the ".subscribe()" method

Imagine having a component structured like this The Initial Code: import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `<pre>{{ ...

Issue: Unable to find 'rxjs/add/operator/map'

In the app.module.ts file, I have attempted to import the map in various projects and it worked smoothly. However, in this particular project, it seems to be causing some issues. import { BrowserModule } from '@angular/platform-browser'; ...