【问题标题】:Display list of users using input value to add names to the list显示使用输入值将名称添加到列表中的用户列表
【发布时间】:2018-09-06 14:53:24
【问题描述】:

我正在尝试显示获取输入值并将其用作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": {} }

我的组件.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
    });
  }
}

我的组件.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>

我会感谢任何愿意提供帮助的好心人。

【问题讨论】:

  • this.users 设置为用户列表的Observable,而不是用户列表本身。见the docs for get()。您需要订阅它。 tutorial has an example of adding an element and updating the list.
  • 专业提示,与手头的问题完全分开:不应使用 GET 请求来更改后端的数据。 POST 请求适用于添加新项目。这不仅仅是一个架构问题,而是一个安全问题,因为 HTTP 服务器通常不会对 GET 请求进行太多验证,因为它们只是获取内容。
  • 嗨。感谢您的回答。我正在阅读文档以尝试解决我的问题 atm,如果我能弄明白,我会更新这篇文章。

标签: angular list typescript input


【解决方案1】:

所以,今天我终于设法解决了我的问题。 但是,如果这是一个很好的解决方案,我不知道。 但是我将把我所做的留在我的代码中,因为它可能会在以后对某人有所帮助。

这是我对 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);
      });
    }
  }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 2015-12-25
    • 2021-05-23
    • 2022-01-13
    • 2017-08-18
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多