对象值未在模板视图中更新

时间:2019-04-04 06:52:33

标签: angular

获取数据后订阅服务时,对象值未在模板视图@angular中更新

int age = currentDate.getYear() - dateOfBirth.getYear();

HTML:

`` 
subscription: Subscription;
userDatafromDB: UserRead;
constructor(
    private _userinfo: UserdetailService
  ) {}
ngOnInit() {
    this.subscription = this._userinfo.UserDetailsChanged$.subscribe(
      (data: UserRead) =>
        data != null
          ? (this.userDatafromDB = data)
          : (this.userDatafromDB = null)
    );
  }``

2 个答案:

答案 0 :(得分:0)

不要在您的subscription()上返回整个语句。尝试将component.ts上的ngOnInit更改为此:

ngOnInit() {
  this.subscription = this._userinfo.UserDetailsChanged$.subscribe(
    (data: UserRead) => {
      data != null
        ? (this.userDatafromDB = data)
        : (this.userDatafromDB = null)
   });
}

然后在您的component.ts上,使用userDatafromDB上的安全导航运算符来保护它免受空值导致的错误。

<h2>EMAIL ::: {{ userDatafromDB?.email }}</h2>

答案 1 :(得分:0)

在这种情况下,我建议使用async管道。它将像您一样订阅,并且您不必处理订阅代码。

*。component.ts

userDetails$: Observable<UserRead>;
constructor(private _userinfo: UserdetailService) {}
ngOnInit() {
    this.userDetails$ = this._userinfo.UserDetailsChanged$;
}

*。component.html

<ng-container *ngIf="userDetails$ | async as userDetails">
   <h2>EMAIL ::: {{ userDetails.email }}</h2>
</ng-container>