angular - 在 Angular 中渲染模板之前加载数据

标签 angular typescript data-binding

我正在使用 Angular 6 并使用单向绑定(bind)。

我在组件中的代码如下。

ngOnInit() {
 this.profile.getUser(1).subscribe((data) => {
  this.userData = this.compiler.constructUserData(data);
 });
}

userData 有一个对象,它有属性。我正在尝试将其数据绑定(bind)到 HTML 中,如下所示

<mat-list-item role="listitem">
          <span matLine>
            <span>First Name: </span>
            <span> {{userData?.first_name}}</span>
          </span>
        </mat-list-item>
        <mat-list-item role="listitem">
          <span matLine>
            <span>Last Name: </span>
            <span> {{userData?.last_name}} </span>
          </span>
        </mat-list-item>
        <mat-list-item role="listitem">
          <span matLine>
            <span>Email: </span>
            <span> {{userData?.email}} </span>
          </span>
        </mat-list-item>
        <mat-list-item role="listitem">
          <span matLine>
            <span>Mobile: </span>
            <span> {{userData.mobile_no}} </span>
          </span>
        </mat-list-item>

这里我在 userData 变量之后使用了 ?。但是当我写?还有最后一项

例如mobile_no 它不显示网络上的任何数据(first_name、last_name、email 或 mobile_no)。但是,如果我从最后一项或任何一项中删除 ? 。数据显示在网页的控制台中。

错误显示如下。

Error description

最佳答案

如果您订阅了 Observable 并且没有在模板中放置 ?,请确保使用 this.userData 初始化最初是一个空对象。

像这样:

userData = {};

我建议您在模板中使用 async 管道,而不是订阅 Observable。假设您将 userData 作为包含 emailfirst_name 等的对象在您的 userData 对象中获取,这看起来像这样:

import { map } from 'rxjs/operators';

...

userData$;

...

ngOnInit() {
  this.userData$ = this.profile.getUser(1).pipe(
    map(data => {
      return this.compiler.constructUserData(data);
    })
  );
}

在你的模板中:

<div *ngIf="userData$ | async as userData">
  <mat-list-item role="listitem">
    <span matLine>
            <span>First Name: </span>
    <span> {{userData.first_name}}</span>
    </span>
  </mat-list-item>
  <mat-list-item role="listitem">
    <span matLine>
            <span>Last Name: </span>
    <span> {{userData.last_name}} </span>
    </span>
  </mat-list-item>
  <mat-list-item role="listitem">
    <span matLine>
            <span>Email: </span>
    <span> {{userData.email}} </span>
    </span>
  </mat-list-item>
  <mat-list-item role="listitem">
    <span matLine>
            <span>Mobile: </span>
    <span> {{userData.mobile_no}} </span>
    </span>
  </mat-list-item>
</div>

Here's a Working Sample StackBlitz for your ref.

关于angular - 在 Angular 中渲染模板之前加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53993922/

相关文章:

android - 在数据绑定(bind)中设置动态布局高度

javascript - 使用函数和返回值设置 "d"时如何修复 d3 解析错误?

javascript - ngOnInit 内的引用错误

Angular 2 : Use CanDeactivate, 但显示模式而不是 window.confirm

php - Laravel Sanctum 身份验证 :sanctum middleware with Angular SPA unauthenticated response

silverlight - 将 ListBox 绑定(bind)到 Silverlight 中的界面属性

angular - 缺少必需的获取参数 Angular 4

javascript - 合并数组中的重复对象

javascript - typescript 函数联合类型缺少调用签名

Angular-cli 构建文件夹结构