Angular 从用户输入获取请求
更新: 我的html模板:Angular 从用户输入获取请求,angular,express,input,get,request,Angular,Express,Input,Get,Request,更新: 我的html模板: <input type="text" (keyup)="onNameKeyUp($event)"> <button (click)="getOneWord()">Get Profile</button> <span>{{translation}}</span> 我在这里越来越绝望了,所以希望有人能把我解开! 我设法从angular服务向express服务器发送get请求。服务器用数据进行响应。 我的问
<input type="text" (keyup)="onNameKeyUp($event)">
<button (click)="getOneWord()">Get Profile</button>
<span>{{translation}}</span>
我在这里越来越绝望了,所以希望有人能把我解开!
我设法从angular服务向express服务器发送get请求。服务器用数据进行响应。
我的问题是,我无法在角度组件中显示服务器返回的数据
这是我的web服务:
getWord(name: string): Observable<Word> {
return this.http.get<Word>('http://localhost:3000/api/words/' + name);
}
但是,要么显示整个数据,要么不显示任何数据。我想要的是,如果用户搜索/输入'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"}];
有一百万种方法可以做到这一点,但我将推荐一些关于您应该做什么的最佳实践,然后提供额外的信息,说明为什么您应该遵循它而不是一些定制方法
- 它的作用类似于组件模板(html)上的“订阅”。与手动订阅和自己设置局部变量相比,使用此选项有很多原因。当模板被销毁时,
管道将自动取消订阅。阻止您使用takeUntil+a主题+Ngondestory(如所见和所述)async
//组件代码
//我们将拥有的财产
公共词$:可见;
恩戈尼尼特(){
//变量后的美元符号是表示其“可观察”的惯例
this.words$=this.getWords()
}
私有getWord(word:string):可观察{
//服务方法返回单词或数据的列表
返回此.wordService.getWord(word)
//我们将使用map操作符获取单词列表(您所说的)
//是否在“数据”中返回?
.pipe(map((dat)=>data.find((dataWord)=>dataWord.spelling==word);
}
起点
A部分
getWord(name: string): Observable<Word> { return this.http.get<Word>('http://localhost:3000/api/words/' + name); }
(二)
如果您的API已修复
你应该把这个词找回来
getOneWord(){ this.webService.getWord(this.spelling) .subscribe(res => console.log(res));
我不知道我做错了什么。它返回的是整个数组,而不是一个对象。让我在console.log(res)时添加它。它在我保存时立即返回整个数组。它甚至没有等我单击submit按钮。hello.1)它在哪一点返回整个数组?2)你能用你的html模板更新你的问题吗?它是在我保存更改时返回的,而不是在我单击button@omar检查这个StackBlitz项目。
getWord(name: string): Observable<Word> { return this.http.get<Word>('http://localhost:3000/api/words/' + name); }
getWord(name: string): Observable<Word[]> { return this.http.get<Word[]>('http://localhost:3000/api/words/' + name); }
theWord;
getOneWord(){ this.webService.getWord(this.spelling) .subscribe((res: Word[]) => { this.theWord = res.find(d => d.spelling === this.spelling )} );
getOneWord(){ this.webService.getWord(this.spelling) .subscribe(res => console.log(res));