0

我是 Angular 的新手,并试图将带有选项组的 mat-select 添加到我的 Angular 6 应用程序中。我有一个现有的 Web API,它有 2 个 URL。一个 URL 返回组,另一个返回给定 groupId 的每个组中的项目。

此页面在加载时进入无限循环。为了排除故障,我尝试在 ngOnInit () 中为 this.groups 添加一个记录器,这样我就可以构造 HTML 使用的数组,但看起来 this.groups/this.items 在 HTML 页面调用之前没有初始化。

我一定是在接近这个错误。我只尝试添加一个 HTML mat-select,其中 mat-optgroups 由 1 个 web 服务确定/mat-options 由另一个 web 服务确定。

我根据这个例子(https://material.angular.io/components/select/overview#creating-groups-of-options)构建了这个:

导航.component.ts

import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import {HttpErrorResponse} from '@angular/common/http';
import {Component, OnInit} from '@angular/core';
import { Group } from '../group';
import { GroupService } from '../group.service';
import { Item } from '../item';
import { ItemService } from '../item.service';

@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.css']
})
export class NavigationComponent implements OnInit {

  groups: Group [] = [];
  items: Item [] = [];
  pokemonControl = new FormControl();


  constructor(private groupService: GroupService, private itemService: ItemService) {}


  ngOnInit () {
    this.getGroups();
    console.log("length: " + this.groups.length); // logs 0 as length
  }

  getGroups(): void {
    this.groupService.getGroups().subscribe(
      data => {
        this.groups = data as Group[];
        console.log(data);
      },
      (err: HttpErrorResponse) => {
        console.log (err.message);
      }
    );

  }

  getItems(department: number): void {
    this.itemService.getItems(department).subscribe(
      data => {
        this.items = data as Item[];
        console.log(data);
      },
      (err: HttpErrorResponse) => {
        console.log (err.message);
      }
    );
  }

}

组服务.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

import { Group } from './group';

@Injectable({
  providedIn: 'root'
})
export class GroupService {

  private groupsUrl = 'http://localhost:8180';

  constructor(private http: HttpClient) { }

   getGroups (): Observable<Group[]> {
    const url = `${this.groupsUrl}/groups`;
    return this.http.get<Group[]>(url);
  }

  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
    console.error(error);
    console.log(`${operation} failed: ${error.message}`);
    return of(result as T);
    };
  }

}

项目服务.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

import { Item } from './item';

@Injectable({
  providedIn: 'root'
})
export class ItemService {

  private itemsUrl = 'http://localhost:8180';

  constructor(
    private http: HttpClient) { }


   getItems (groupId: number): Observable<Item[]> {
    const url = `${this.itemsUrl}/groups/${groupId}/items`;
    return this.http.get<Item[]>(url);
  }

  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);
      console.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    };
  }

}

HTML

<mat-select [formControl]="pokemonControl">
  <mat-optgroup *ngFor="let group of group.groupList" [label]="group.groupName"
                [disabled]="group.disabled">
    <mat-option *ngFor="let item of getItems(group.groupId).itemList" [value]="item.itemId">
      {{item.itemName}}
    </mat-option>
  </mat-optgroup>
</mat-select>
4

1 回答 1

0

检查这一行:

let item of getItems(group.groupId).itemList

这条指令在另一个里面*ngFor,所以它被执行的次数与group.groupList.

如果它是 10 个元素长,getItems(...)方法将被调用 10 次,每次它会产生一个HTTPRequest,并且在异步应答之后,它会覆盖items变量。

所以行为是不可预测的,并且items变量不可用,因为它在几秒钟内改变了几次。你所说的体验就像一个无限循环,它可能只是响应新变化产生新变化的变化检测。

解决方案:

如果您需要同步使用多个可观察对象,请不要订阅它们!

Observables 是异步的。您无法猜测它何时会执行订阅代码,即订单或何时执行。

Rxjs 提供了几种操作符来解决这个问题。您可以在此处检查组合运算符。

于 2018-08-29T16:45:43.063 回答