-2

I'm fetching the data from json file in services and subscribing it from my component. I'm doing some condition check with the data, once it matches I want to stop subscribing but it's not working and still its subscribing.

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';
    }
  });
});
Hamid Asghari
  • 4,954
  • 3
  • 20
  • 32
Jagadeesh
  • 738
  • 6
  • 24
  • why are you `subscription.unsubscribe();` in forEach? – Krishna Rathore Aug 21 '18 at 05:58
  • By the time you get your json from the http call the observable has completed. Check https://stackoverflow.com/questions/48516432/do-we-need-to-unsubscribe-from-http-calls-in-angular and https://stackoverflow.com/questions/35042929/is-it-necessary-to-unsubscribe-from-observables-created-by-http-methods – Tim Martens Aug 21 '18 at 06:12
  • There is no need to unsubscribe .it will be automatically unsubscribe on request completion. – Akj Aug 21 '18 at 06:19

2 Answers2

2

Angular HTTPClient

The angular HTTPClient will unsubscribe automatically on request completion. That is either on success or on error.

Also at the time you are unsubscribing, the http request is already returned a success so it is completed.

What i am understanding from your code is that, you are expecting the unsubscribe to stop your loop. Unsubscribing a Subscription is not meant to stop your foreach loop. To stop the foreach loop simply use return or break.

Hamid Asghari
  • 4,954
  • 3
  • 20
  • 32
-3

Your unsubscribe is inside the subscribe call.. It should be outside as the subscribe call will execute only after you get response from server.

If you want to unsubscribe request then you should unsubcribe it outside.

If you want to break the foreach loop then use return.

Let me know if you need any futher clarification

Krishna
  • 543
  • 5
  • 23