Angular 6 - problem executing nested .subscribe()

2019-08-27 05:23发布

I've created an app with user authentication system. Firstly I check if user with given registration e-mail exists and if does not - I call registration service.

register.component.ts

registerUser(email: String, password: String) {
  let found = false;
  this.authService.findUser(email).pipe(
    tap(res => { console.log(res.status);
      if (res.status === 202) { found = true; } else if (res.status === 200) { found = false; } else {found = null; }}),
    concatMap(res => {
      console.log(found);
      if (found) {
        this.snackBar.open('E-mail already taken.', 'Ok', { duration: 3000 });
      } else if (!found) {
        this.authService.registerUser(email, password).subscribe(res2 => {
          /* CODE DOES NOT EXECUTE - START */
          console.log(res2.status);
          if (res2.status === 201) {
            this.router.navigate(['/list']);
          } else {
            this.snackBar.open('Unable to add new user.', 'Try later', { duration: 3000 });
          }
          /* CODE DOES NOT EXECUTE - END*/
        });
      } else {
        this.snackBar.open('Checking e-mail address failed.', 'Try later', { duration: 3000 });
      }
      return of(res);
    })
  ).subscribe();
}

The user is registered properly, but the marked code is not executed. In AuthService - {observe: 'response'} is added to both get (findUser) and post (registerUser) requests.

1条回答
倾城 Initia
2楼-- · 2019-08-27 06:07

You should not subscribe to the inner observable, correct approach is to combine observables to just one and subscribe to it:

registerUser(email: String, password: String) {
  this.authService.findUser(email)
    .pipe(
      flatMap(res => {
        let found = null;

        if (res.status === 202) {
          found = true;
        } else if (res.status === 200) {
          found = false;
        }

        console.log(found);

        if (found) {
          this.snackBar.open('E-mail already taken.', 'Ok', { duration: 3000 });

          return of(res);
        }

        return this.authService.registerUser(email, password);
      }),
    )
    .subscribe(res2 => {
      console.log(res2.status);
      if (res2.status === 201) {
        this.router.navigate(['/list']);
      } else {
        this.snackBar.open('Unable to add new user.', 'Try later', { duration: 3000 });
      }
    });
}

Note that I also simplified your code, no need for tap and concatMap. Other thing was that condition for found and !found - the third else branch could never be executed so I removed that as well.

https://www.learnrxjs.io/operators/transformation/mergemap.html

查看更多
登录 后发表回答