【问题标题】:Angular Autocomplete can't get id value and display object propertiesAngular Autocomplete 无法获取 id 值并显示对象属性
【发布时间】:2020-08-11 21:32:15
【问题描述】:

首先,我是 Angular 的新手。我正在开发一个集成 AngularJS 作为前端和 Yii2 作为后端的应用程序。到目前为止,一切都很好,但在过去的几周里,我正在处理一个 Angular Material 头痛。我一直在寻找很多,但我找不到解决方案。

我正在尝试编写一个包含大约 10 个自动完成材料元素的表单。我的数据由 Angular 服务中的 API REST 作为可观察对象获取。在每个自动完成元素中,我可以轻松地显示选项,但是当我尝试绑定/获取对象的 id 时问题就来了。 DisplayWith 只是给了我 id 的值,而我期望至少是完整的对象,所以我可以返回对象的名称和其他属性。我希望 [displayWith] 将整个对象还给我,以便我可以处理可以返回显示的属性。

我已经看到如何使用对象数组或简单数组来执行此操作,但我不知道如何使用我的 Rest Api 中的 observables 来执行此操作。另外,我不知道是否真的有效,例如,在一个表单中管理这么多 observable。

我读过this feature,但不太可能对我没有帮助。即使我找到了一些解决方案,我也没有为 Observables 找到任何解决方案。也许我面对的整个事情都是错误的。在此先感谢,我真的很感谢有人可以帮助我。

到目前为止,这只是我的一个自动完成元素的代码。

角度组件

import { Component, OnInit } from '@angular/core';
import { FormBuilder,FormGroup, Validators, FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { startWith, debounceTime, switchMap, map, distinctUntilChanged } from 'rxjs/operators';

import { DedicacionI } from '../../../models/dedicacion.interface'
import { DedicacionesService } from 'src/app/services/dedicaciones.service';

export class DocenteAltaComponent implements OnInit {
 
  myForm = new FormGroup()

  myControlDedicaciones = new FormControl();
  dedicacionesList: Observable<DedicacionI[]>;
  filteredOptionsDedicaciones: Observable<DedicacionI[]>;

  constructor (
    public fb:FormBuilder,

    private dedicaciones:DedicacionesService,
    ) 
    
    { 

      this._getDedicacionesData();

      this.filteredOptionsDedicaciones = this.myControlDedicaciones.valueChanges.pipe(
        startWith(null),
        debounceTime(200),
        distinctUntilChanged(),
        switchMap(val => {
          return this._filterDedicaciones(val || '')
        })
      )
    }
    
  private _getDedicacionesData():void {
    this.dedicacionesList = this.dedicaciones.getDedicaciones();
  }

  private _filterDedicaciones(val: string) {
    return this.dedicacionesList.pipe(
      map(response => response.filter(option => {
        let aux = option.denominacion.toString();
        return aux.toLowerCase().indexOf(val.toString().toLowerCase()) === 0
      }))
    )
  }

  public displayDedicacion (dedicacionSel): string {
    if (dedicacionSel != null){
      return dedicacionSel.denominacion + " (" + dedicacionSel.codigo + ")";
    }else{
      return "";
    }
  }
}  

Angular html

<form [formGroup]="myForm" (ngSubmit)="save(myForm.value)">

    <!-- Dedicaciones -->
    <p>
        <mat-form-field class="example-full-width">
        <input type="text"
            placeholder="Dedicación"
            aria-label="Number"
            matInput
            [formControl]="myControlDedicaciones"
            [matAutocomplete]="autoDededicacion">
            <mat-autocomplete autoActiveFirstOption #autoDededicacion="matAutocomplete" [displayWith]="displayDedicacion">
            <mat-option *ngFor="let option of filteredOptionsDedicaciones | async" [value]="option">
                <p>{{option.denominacion}} ({{option.codigo}}) </p>
                                
            </mat-option>
            </mat-autocomplete>
        </mat-form-field>
    </p>
    <!-- /.Dedicaciones -->

</form>

角度服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DedicacionI } from '../models/dedicacion.interface';

@Injectable()

export class DedicacionesService {

  constructor(private http:HttpClient) { }

  getDedicaciones() {

    return this.http.get<DedicacionI[]>("http://localhost/yii2-tests/rest/web/index.php/v1/dedicaciones")
          
  }

}

【问题讨论】:

    标签: angular autocomplete angular-material angular2-observables


    【解决方案1】:

    您似乎没有订阅服务调用,因此您需要这样做,否则您将永远无法获得任何数据。像这样的:

        private _getDedicacionesData():void {
            this.dedicaciones.getDedicaciones().subscribe(
            
            returnValueFromService =>{        
                this.dedicacionesList = returnValueFromService.data
    }
            );          
    }
    

    您可能希望在开始实施材料控制之前“证明”您可以获取数据。一点一点地构建是个好习惯

    您还应该在 ngoninit 中进行服务调用,因为在构造函数中这样做是不好的做法

    【讨论】:

    • 我确实得到了数据。问题是,一旦用户选择了自动完成选项,我就无法同时获取 id 值和显示对象属性。
    • 不确定这是一个角度问题 tbh 或者它与 observables 有什么关系......但如果你有 ID,那么你可以使用 filterOptionsDedicaciones.filter( x => x.id = dedicacionSel) ...
    猜你喜欢
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 2021-04-29
    相关资源
    最近更新 更多