使用输入值向列表中添加名称来显示用户列表

时间:2018-09-06 14:53:25

标签: angular list typescript input

我试图显示获取输入值并将其用作get()方法的参数的用户列表。我得到了get()的返回,并使用push将其插入到对象中,然后尝试在模板中显示该对象。

我想:

  1. 搜索用户。
  2. 显示此用户。
  3. 搜索其他用户。
  4. 与第一个用户一起显示其他用户。

但是模板显示错误:

{ "_isScalar": false, "source": { "_isScalar": false, "source": { "_isScalar": false, "source": { "_isScalar": true, "value": { "url": "http://localhost:3000/users", "body": null, "reportProgress": false, "withCredentials": false, "responseType": "json", "method": "GET", "headers": { "normalizedNames": {}, "lazyUpdate": null, "headers": {} }, "params": { "updates": [ { "param": "user", "value": "Teste", "op": "s" } ], "cloneFrom": null, "encoder": {}, "map": {} }, "urlWithParams": "http://localhost:3000/users?user=Teste" } }, "operator": { "concurrent": 1 } }, "operator": {} }, "operator": {} }

我的component.ts:

import { HttpClient, HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-info',
  templateUrl: './info.component.html',
  styleUrls: ['./info.component.scss']
})
export class InfoComponent implements OnInit {
  public buscar: string;
  users: any;
  private readonly url = 'http://localhost:3000/users';
  select: any;
  usuario = [
    {
      user: ''
    }
  ];

  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.users = this.http.get(this.url);
  }

  getDados(event) {
    if (event.keyCode === 13) {
      const params = new HttpParams().set('user', this.buscar);
      this.select = this.http.get(this.url, { params });
    }

    this.usuario.push({
      user: this.select
    });
  }
}

我的component.html:

<igx-input-group type="search" class="search">
  <igx-prefix>
    <igx-icon>search</igx-icon>
  </igx-prefix>
  <input #search igxInput placeholder="Buscar" (keydown)="getDados($event)" [(ngModel)]="buscar">
  <igx-suffix *ngIf="search.value.length > 0" (click)="searchContact = null">
    <igx-icon>clear</igx-icon>
  </igx-suffix>
</igx-input-group>

<div class="list-sample">
  <igx-list>
    <igx-list-item isHeader="true">Users</igx-list-item>
    <igx-list-item #item *ngFor="let users of users | async">
      <div class="item-container">
        <div class="contact">
          <div  class="contact__info">
            <span class="id">{{users.id}} </span>
            <span class="user">{{users.user}}</span>
          </div>
        </div>
      </div>
    </igx-list-item>
  </igx-list>
</div>
<p *ngFor="let usuario of usuario">{{ usuario.user | json }}</p>

我会感激任何愿意帮助的人。

1 个答案:

答案 0 :(得分:0)

所以,今天我终于设法解决了我的问题。 但是,如果这是一个好的解决方案,请使用idk。但是,我将把我对代码所做的事情留在这里,因为这可能会在以后对某人有所帮助。

这是我对component.ts所做的更改:

import { HttpClient, HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Observable, throwError, } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

@Component({
  selector: 'app-info',
  templateUrl: './info.component.html',
  styleUrls: ['./info.component.scss']
})
export class InfoComponent implements OnInit {
  public buscar: string;
  users: Observable<any>;
  private readonly url = 'http://localhost:3000/users';
  select: {id: number; user: string} [];
  list: { user: string } [];
  showUser: { user: string } [];

  constructor(private http: HttpClient) {
    this.showUser = new Array<any>();
    this.list = new Array<any>();
  }

  ngOnInit() {
    this.getUsers();
  }

  getUsers() {
    this.http.get<{ id: number; user: string; }[]>(this.url)
    .pipe(
      map(data => {
        return data.map(el => ({ id: el.id, user: el.user }));
      }),
      catchError(error => {
        return throwError('Deu erro!');
      })
    )
    .subscribe((transformedData: { id: number, user: string }[]) => {
      this.select = transformedData;
    });
  }

  getDados(event) {
    if (event.keyCode === 13) {
      const params = new HttpParams().set('user', this.buscar);

      this.http.get<{ user: string; }[]>(this.url, { params })
      .pipe(
        map(data => {
          return data.map(el => ({ user: el.user }));
        }),
        catchError(error => {
          return throwError('Deu erro!');
        })
      )
      .subscribe((transformedData: { user: string }[]) => {
        this.list = transformedData;
        console.log(this.list[0].user);
        this.showUser.push({
          user: this.list[0].user
        });
        console.log(this.showUser);
      });
    }
  }
}

欢迎对此解决方案进行任何审查,如果您有更好的解决方案,请告诉我。谢谢。