Angular окно поиска не работает должным образом - PullRequest
0 голосов
/ 07 января 2020

Привет! Я добавил поисковый ящик в свой код для поиска в таблице пользователей и получения заданного пользователя и всех его свойств (имя, адрес электронной почты и т. Д. c ..). Он работает нормально, возвращает все, что мне нужно, но сразу после того, как я выбрал предпочтительного пользователя, например, я поискал «Работник» и там есть Работник1, Работник2, Работник3, и я выбираю Работника1, вместо того, чтобы возвращать только его свойства, я вижу свойства ( имя, адрес электронной почты) двух других в поле ввода.

вот мой код:

<div class="material-input">
      <mat-form-field class="form-group">
        <input id="userNameInput" matInput placeholder="Search user name" formControlName="userName" for="search-box"
          #searchBox id="search-box" (input)="search(searchBox.value)" [matAutocomplete]="auto">
        <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
          <mat-option *ngFor="let username of mockLdap | async" [value]="username.userName">
            {{username.userName}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
    </div>

<div class="material-input">
      <mat-form-field class="form-group" appearance="outline">
        <mat-label>First name</mat-label>
        <input matInput readonly formControlName="firstName">
        <mat-list *ngFor="let username of mockLdap | async">
          {{username.firstName}}
        </mat-list>
      </mat-form-field>
    </div>

что-то здесь не так, но я пытаюсь либо показать все, либо ничего и не может показать только выбранные свойства пользователя

вот мой компонент:

import { Component, OnInit, forwardRef } from '@angular/core';
import { HttpClientService, Employee } from '../service/http-client.service';
import { Router } from "@angular/router";
import { FormGroup, FormBuilder, Validators, FormsModule, NgForm } from '@angular/forms';
import { LDAPUsers } from "../LDAPUsers";
import { Observable, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'

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

  checkboxTrue = true;

  LDAPUsers: LDAPUsers;
  ldapUsers: Observable<LDAPUsers[]>;
  user: FormGroup;
  // Admin: any;
  // Supervisor: any;
  currentlyDisabled: string;
  permissions: string[] = ['Admin', 'Supervisor'];
  mockLdap: Observable<LDAPUsers[]>;
  private searchTerms = new Subject<string>();

ngOnInit(): void {
    this.user = this.formBuilder.group({
      id: [],
      userName: [''],
      firstName: [''],
      lastName: [''],
      mobile: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
    });
    this.user.setErrors({ required: true });
    this.user.valueChanges.subscribe((newValue) => {
      if (newValue.admin === true || newValue.supervisor === true || newValue.enabled === true) {
        this.user.setErrors(null);
      } else {
        this.user.setErrors({ required: true });
      }
    });
    this.httpClientService.getLDAPUser('username').subscribe
      (data => {
        this.LDAPUsers = data;
        console.log(JSON.stringify(data));

        this.user.patchValue(data);
      }
      )

    this.mockLdap = this.searchTerms.pipe(
      debounceTime(1000),

      distinctUntilChanged(),

      switchMap((term: string) => this.httpClientService.searchLDAPUsers(term))
    );

  }

  createEmployee(): void {
    let formattedObject = this.userManipulate(this.user.value);
    console.log(JSON.stringify(formattedObject));
    this.httpClientService.createEmployee(formattedObject)
      .subscribe(data => {
        this.router.navigate(['employee']);
        alert("User created successfully.");

      });
  };
}

класс mockLdap:

export class LDAPUsers {
    userName: string;
    firstName:string;
    lastName: string;
    mobile: number;
    email: string;
}
...