首页 > 解决方案 > 来自用户输入的角度获取请求

问题描述

更新:我的 html 模板:

 <input type="text" (keyup)="onNameKeyUp($event)">
 <button (click)="getOneWord()">Get Profile</button>
 <span>{{translation}}</span>

ts。零件:

onNameKeyUp(event: any){
this.spelling= event.target.value;    

我在这里变得绝望,所以希望有人能帮我解开!我设法将一个获取请求从一个角度服务发送到一个快速服务器。服务器响应数据。我的问题是我无法以角度组件显示服务器返回的数据。

这是我的网络服务:

  getWord(name: string): Observable<Word> {
  return this.http.get<Word>('http://localhost:3000/api/words/' + name);
 }

然后我将这个服务注入到一个组件中,调用它:

getOneWord(){
this.webService.getWord(this.spelling)
.subscribe(res =>
 console.log(res));

但是,要么显示全部数据,要么不显示。我想要的是,如果用户搜索/输入“aman”,则只会返回第一个对象。

数据是:

var words=[
{spelling: "aman", category: "noun", translation: "water"},
{spelling: "azzel", category: "verb", translation: "run"},
{spelling: "aberkan", category: "adjective", translation: "black"},
{spelling: "gar", category: "preposition", translation: "between"}];

标签: angularexpressinputgetrequest

解决方案


初始点

A部分

getWord(name: string):      Observable<Word> { return this.http.get<Word>('http://localhost:3000/api/words/' + name); }
  1. 您的 API 应该返回与该单词匹配的项目,但您却得到了整个单词。在那一端似乎有一个错误
  2. 您需要更新您的服务以期望单词数组而不是单个单词

更新这个

getWord(name: string): Observable<Word[]> { return this.http.get<Word[]>('http://localhost:3000/api/words/' + name); }

B部分

如果您仍然收到一系列单词。

1)声明一个全局变量

theWord;

2)

getOneWord(){ this.webService.getWord(this.spelling) .subscribe((res: Word[]) => { this.theWord = res.find(d => d.spelling === this.spelling )}  );

如果您的 API 已修复

你可能应该得到回复。

  getOneWord(){ this.webService.getWord(this.spelling) .subscribe(res => console.log(res));

推荐阅读