Search code examples
angularexpressinputgetrequest

angular get request from user input


UPDATE: my html template:

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

ts. component:

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

I am getting desperate here, so hopefully someone will get me unstuck! I managed to send a get request from an angular service to an express server. The server responds with the data. My problem is that I cannot display the data returned by the server in an angular component.

this is my web-service:

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

Then I am injecting this service in a component, calling it:

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

However, either the whole data is displayed or none of it. What I want is that if the user searches/enters 'aman', only the first object will be returned.

the data is:

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"}];

Solution

  • Starting point

    Part A

    getWord(name: string):      Observable<Word> { return this.http.get<Word>('http://localhost:3000/api/words/' + name); }
    
    1. your API is supposed to return item that matches the word but instead you are getting the whole word back. there seems to be a bug on that end
    2. you need to update your service to expect an array of word rather than a single word

    Update this

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

    Part B

    if you are still getting an array of word back.

    1) declare a global variable

    theWord;
    

    2)

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

    if your API has been fixed

    you should probably be getting the word back.

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