Angular从2个不同的Web服务填充mat-optgroup / mat-options

时间:2018-08-29 16:29:59

标签: angular angular6 angular-httpclient angular-material-6

我是Angular的新手,正在尝试向我的Angualr 6应用程序添加带选项组的垫选。我有一个具有2个URL的现有Web API。一个URL返回组,另一个URL返回给定groupId的每个组中的项目。

此页面在加载时进入无限循环。为了进行故障排除,我尝试在ngOnInit()中为this.groups添加一个记录器,以便可以构造HTML使用的数组,但看起来像this.groups / this.items不会被HTML页面调用直到初始化。 >

我一定要解决这个错误。我只尝试添加HTML mat-select,其中mat-optgroup由1个webservice确定/ mat-options由另一个webservice确定。

我已根据此示例(https://material.angular.io/components/select/overview#creating-groups-of-options)对此进行了解释:

navigation.component.ts

$scope.$watch('vm.institution.employees', function(newValue, oldValue) {
  if (newValue.occupation != oldValue.occupation || newValue.salary != oldValue.salary) {
    vm.xx = 'test';
  }
});

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

}

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

}

HTML

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

}

1 个答案:

答案 0 :(得分:0)

检查此行:

let item of getItems(group.groupId).itemList

该指令位于另一个*ngFor中,因此它的执行时间与group.groupList的长度一样。

如果长度为10个元素,则getItems(...)方法将被调用10次,并且每次将产生 HTTPRequest ,并且在异步回答后,它将覆盖{ {1}}变量。

因此,该行为是不可预测的,并且items变量不可用,因为它在几秒钟内会多次更改。您所说的体验就像一个无限循环,很可能只是变更检测对新变更做出响应而产生新变更。

解决方案:

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

可观察对象是异步的。您无法猜测何时执行订阅代码,即订购顺序或何时

Rxjs提供了多个运算符来解决此问题。您可以检查合并运算符here