0

How do I pass form input value to an api query. For example I am using the itunes api, the url constructs of:

https://itunes.apple.com/search?term=searchQuery&entity=album&limit=10

Where the searchQuery is that is what needs to be populated, if I hard code the value of public searchQuery = ''; it works. But need it to work with the input value of the search.

So my files are:

service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})
export class ApiService {

  api: string = 'https://itunes.apple.com/search?term=';

  constructor(
    private http: HttpClient,
  ) { }

  getAll(searchTerm): Observable<any> {
    return this.http.get(this.api + searchTerm + '&entity=album&limit=10')
    .pipe(
      catchError(this.handleError)
    );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.log(error.error.message)

    } else {
      console.log(error.status)
    }
    return throwError(
      console.log('Something is wrong!'));
  };
}

Component.ts

import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../../services/api.service';
import { FormGroup, FormControl } from '@angular/forms';
import { FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.scss']
})
export class ContentComponent {

  public data = [];
  public apiData: any;
  public searchQuery = '';

  constructor(private service: ApiService) { }

  getAll() {
    this.service.getAll(this.searchQuery).subscribe((results) => {
      console.log('Data is recieved - Result - ', results);
      this.data = results.results;
    })
  }

  ngOnInit() {

  }
}

HTML

<div class="jumbotron hero">
  <div class="container">
    <h1 class="display-4 text-center header mb-5">SEARCH</h1>
    <form>
      <div class="row">
        <div class="col-8">
          <div class="form-group">
            <label for="inputPassword2" class="sr-only">Search</label>
            <input type="text" class="form-control form-control-lg" id="searchQuey"
              placeholder="Search iTunes..." value="SearchQuery">
          </div>
        </div>
        <div class="col-4">
            <button type="button" (click)="getAll()" class="btn btn-primary btn-block btn-lg">Get All</button>
          </div>
      </div>
    </form>
  </div>
</div>
<div class="container" >
  <table class="table">
    <thead class="thead-light">
      <tr>
        <th>Artwork</th>
        <th>Artist</th>
        <th>Title</th>
        <th>Genre</th>
        <th>Price</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let user of data">
        <td><img src="{{user.artworkUrl60}}"></td>
        <td>{{user.artistName}}</td>
        <td>{{user.collectionName}}</td>
        <td>{{user.primaryGenreName}}</td>
        <td>{{user.collectionPrice}}</td>
      </tr>
    </tbody>
  </table>
</div>

2 Answers 2

1

You need to have a way to pass the value from the function on the .TS file to the service method,

Component.ts

Search(){
   this.service.getAll(this.SearchQuery).subscribe((results) => {
      console.log('Data is recieved - Result - ', results);
      this.data = results.results;
    })
}

and in service.ts

getAll(searchTerm): Observable<any> {
    return this.http.get(this.api + searchTerm + '&entity=album&limit=10')
    .pipe(
      catchError(this.handleError)
    );
  }

use ngModel with search

 <input type="text" [(ngModel)]="SearchQuery"  class="form-control form-control-lg" id="searchQuey"  placeholder="Search iTunes..." value="">
Sign up to request clarification or add additional context in comments.

5 Comments

Using [{ngModel)] seems to break the project? throws an error?
are you using template driven form?
Error: Template parse errors: Can't bind to 'ngModel' since it isn't a known property of 'input'. (" <label for="searchQuery" class="sr-only">Search</label> <input type="text" [ERROR ->][(ngModel)]="SearchQuery" class="form-control form-control-lg" placeholder="Search iTunes..." value="): ng:///AppModule/ContentComponent.html@8:31
0

Use this :-

        <label for="inputPassword2" class="sr-only">Search</label>
        <input type="text" class="form-control form-control-lg" id="searchQuey" [(ngModel)]="searchQuey"
          placeholder="Search iTunes..." value="" name="searchQuey">

In TS:-

searchQuey:any;    // declare above constructor

getAll() {
if(this.searchQuery != '' || this.searchQuery != undefined){
 this.service.getAll(this.searchQuery).subscribe((results) => {
  console.log('Data is recieved - Result - ', results);
  this.data = results.results;
})
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.