【问题标题】:Angular model loading before select list items are loaded在加载选择列表项之前加载角度模型
【发布时间】:2020-06-13 17:25:22
【问题描述】:

我有一个选择列表,其中项目是从可观察的 API 调用中加载的

  getAccounts(): Observable<IAccount[]> {
    let token = localStorage.getItem("jwt");

    // fetch the accounts from the server
    return this.http.get<IAccount[]>(this.baseUrl + "api/account/search",
      {
        headers: new HttpHeaders({
          "Authorization": "Bearer " + token,
          "Content-Type": "application/json"
        })
      });
  }

在组件中,我与其他服务一起调用此服务来获取选择列表项的所有参考数据。我也在调用一个服务来获取与组件相关的模型。

  ngOnInit() {
    this.loadFormReferences();
    this.getInvoice();
  }

  async loadFormReferences() {
    return await Promise.all([
      this.contactService.getContactSummaries(),
      this.productService.getProducts(),
      this.accountService.getAccounts()
    ]).then(res => {
      res[0].subscribe(res => {
          this.customers = res;
          console.log(this.customers);
        }),
        res[1].subscribe(res => {
          this.products = res;
          console.log(this.products);
        }),
        res[2].subscribe(res => {
          this.accounts = res;
          console.log(this.accounts);
        });
    });
  }


 getInvoice() {
    var id = this.activatedRoute.snapshot.params["id"];
    this.editMode = true;

    this.invoiceService.getInvoice(id).subscribe(res => {
        this.invoice = res;
      },
      error => console.error(error));
 }

问题是组件模型在加载所有选择列表项之前加载,导致未选择项。如果参考数据确实在模型之前加载,那么一切都会正确显示。

如何强制它在加载和显示模型之前加载参考数据?或者我可以在项目完成后更新所选项目吗?我正在使用以下 html 在自定义自动完成下拉菜单中显示项目。

        <ng-container matColumnDef="account">
          <mat-header-cell *matHeaderCellDef> Account </mat-header-cell>
          <mat-cell *matCellDef="let element">
            <autocomplete id="HireLine-AccountName-" [ngModel]="element?.accountId" (ngModelChange)="element.accountId = $event" [items]="accounts" key="id" value="name"></autocomplete>
          </mat-cell>
        </ng-container>

【问题讨论】:

  • 您知道应该避免将 jwt 令牌存储在 localStorage 中并仅将其保留在内存中吗?

标签: angular drop-down-menu angular-observable


【解决方案1】:

我通过使用 *ngIf 将页面内容包装在一个 Div 中来解决此问题,该 *ngIf 检查参考数据是否具有值。

<div class="content" *ngIf="customers && accounts && products">
...
</div> 

有人对更好的方法有建议吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多