Как сделать так, чтобы получить значение перед выполнением наблюдаемой? - PullRequest
0 голосов
/ 30 августа 2018

У меня есть код, в котором наблюдаемое выполняется перед кодом, который предшествует ему, и значение, которое оно должно использовать для запроса данных (this.currentAccount.id), еще не достигнуто, когда оно выполняется.

Как я могу изменить его, чтобы убедиться, что идентификатор есть?

Мне нужно иметь значение: this.currentAccount.id; перед запросом query ['userId.equals'] = this.currentAccount.id; выполняется.

console.log('Print 1st: ', this.currentAccount.id); печатается после console.log('Print second', this.users);

ngOnInit() {
    this.isSaving = false;
    this.principal.identity().then(account => {
        this.currentAccount = account;
        console.log('Print 1st: ', this.currentAccount.id);
    });
    this.activatedRoute.data.subscribe(({ community }) => {
        this.community = community;
    });
    const query = {
        };
    if ( this.currentAccount.id != null) {
        query['userId.equals'] = this.currentAccount.id;
    }
    this.userService
        .query(query)
        .subscribe(
                (res: HttpResponse<IUser[]>) => {
                    this.users = res.body;
                },
                (res: HttpErrorResponse) => this.onError(res.message)
        );
    console.log('Print second', this.users);

Ответы [ 2 ]

0 голосов
/ 30 августа 2018

Используйте вызов функции внутри подписки. Функция будет выполняться только после завершения подписки.

this.userService.query(query)
  .subscribe((res: HttpResponse<IUser[]>) => {
    this.doSomething(res);
  }, (res: HttpErrorResponse) => this.onError(res.message);

doSomething(res) {
  this.users = res.body;
  console.log(this.users);
  ...
}
0 голосов
/ 30 августа 2018

Ваш журнал должен находиться в подписке следующим образом:

this.userService
    .query(query)
    .subscribe(
            (res: HttpResponse<IUser[]>) => {
                this.users = res.body;
                console.log('Print second', this.users);
            },
            (res: HttpErrorResponse) => this.onError(res.message)
    );

Редактировать: Переместите следующий код (вместе с каждым зависимым фрагментом кода):

 if ( this.currentAccount.id != null) {
        query['userId.equals'] = this.currentAccount.id;
 }

к подписке, в которой вы устанавливаете текущую учетную запись, поэтому она становится такой:

this.principal.identity().then(account => {
  this.currentAccount = account;
  console.log('Print 1st: ', this.currentAccount.id);

  const query = {
  };
  if (this.currentAccount.id != null) {
    query['userId.equals'] = this.currentAccount.id;
  }
  this.userService
    .query(query)
    .subscribe(
      (res: HttpResponse<IUser[]>) => {
        this.users = res.body;
      },
      (res: HttpErrorResponse) => this.onError(res.message)
    );
});

this.activatedRoute.data.subscribe(({ community }) => {
  this.community = community;
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...