如何确保在执行可观察值之前获取值?

时间:2018-08-30 08:11:38

标签: angular rxjs

我有一个代码,其中可观察的对象在其之前的代码之前被执行,并且它在查询数据时应使用的值(this.currentAccount.id)还不存在。

如何更改它以确保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 :(得分:0)

您的日志语句应像这样驻留在订阅中:

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;
});

答案 1 :(得分:0)

在订阅中使用函数调用。仅在订阅完成后,该函数才会执行。

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);
  ...
}