angular - 来自用户输入的角度获取请求
问题描述
更新:我的 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"}];
解决方案
初始点
A部分
getWord(name: string): Observable<Word> { return this.http.get<Word>('http://localhost:3000/api/words/' + name); }
- 您的 API 应该返回与该单词匹配的项目,但您却得到了整个单词。在那一端似乎有一个错误
- 您需要更新您的服务以期望单词数组而不是单个单词
更新这个
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));
推荐阅读
- java - Android studio gradle 与 firebase 同步错误:响应 204:No Content 没有内容
- progressive-web-apps - 内容的后台同步
- git - 克隆 git 存储库后不是 git 存储库
- ruby-on-rails - Ruby On Rails 将 JSON 转换为 firebase
- r - 使用 R 的 bizdays 包为每日股价数据创建工作日日历的问题
- python - 在 pyspark 中选择包含字符串的列
- jquery - 通过 tbody 而不是 tr 元素进行 DataTable 分页
- node.js - 猫鼬中的最小和最大数量验证
- java - 如何在 MQTT 中接收发件人的姓名
- java - 根据 HTTP 规范,“*”是内容类型的有效通配符吗?