Angular 6 - problem executing nested .subscribe() “next” function

南楼画角 提交于 2019-12-24 19:47:33

问题


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:


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



来源:https://stackoverflow.com/questions/52345024/angular-6-problem-executing-nested-subscribe-next-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!