Вложенная наблюдаемая в Angular 5 - PullRequest
0 голосов
/ 26 апреля 2018

Этот код ниже - мой вложенный наблюдаемый код. но я хочу изменить свой код более умным способом. поэтому я хотел бы изменить этот код, чтобы не использовать вложенный способ.

Как я могу изменить этот код не вложенным способом ??

user: User;
places: Place[];
user_id: string;

this.loginService.getLoginData(email, password).subscribe(
  res1 => {
    this.user = res1;
    this.storageService.saveUserInfo(this.user.userinfo);

    this.loginService
      .getPlaces(this.user.userinfo.token)
      .subscribe(
        res2 => {
          this.places = res2;
          const placeList = this.places.result.place_list.map(place => {
            return place.place_cd;
          });
          const userInfo = new UserInfoImpl(
            this.user.userinfo.email,
            this.user.userinfo.name,
            placeList
          );
          const account = new AccountImpl(
            this.user.userinfo.token,
            userInfo
          );
          this.loginService.postAccount(account).subscribe(
            res3 => {
              this.user_id = res3;
              if (this.user_id) {
                this.storageService.saveUserId(this.user_id);
              }
            },
            err => {
              console.log('err!!! ', err.message);
            }
          );
        },
        err => {
          console.log('err!!! ', err.message);
        }
      );
  },
  err => {
    console.log('err!!! ', err.message);
  }
);

1 Ответ

0 голосов
/ 26 апреля 2018

Вы, вероятно, хотите использовать оператор .concatMap. Хотя .mergeMap .switchMap тоже подойдет.

Упрощенный код:

this.loginService.getLoginData()
    .do((data) => this.storeTheData)
    .concatMap((logindata) => this.loginService.getPlaces())
    .concatMap((placesdata) => this.loginService.postAccount())
    .subscribe()

Поскольку у вас действительно много побочных эффектов, а ваш код не является полностью реактивным, к этому также существует другой подход. Вы можете прослушать сохраненные изменения данных для входа, чтобы загрузить другие данные для вас. Я собираюсь изложить простую версию того, что может не иметь особого смысла.

class Store {
    loginData = new ReplaySubject<LoginData>(1);
    placesData = new ReplaySubject<PlacesData>(1);
}

class AuthService {
    constructor(private store: Store, private http: Http) {

    }

    login() {
            this.http.post("login").subscribe(data => this.store.loginData.next(data));
    }
}

class PlacesService {
    constructor(store: Store, http: Http) {
        store.loginData
             .switchMap((loginData) => http.get("places" + loginData.placesId))
             .subscribe(places => store.places.next(places)
    }
}
...