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>
Sole
  • 3,100
  • 14
  • 58
  • 112

2 Answers2

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="">
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Using `[{ngModel)]` seems to break the project? throws an error? – Sole Nov 17 '19 at 03:23
  • are you using template driven form? – Sajeetharan Nov 17 '19 at 03:24
  • Error: Template parse errors: Can't bind to 'ngModel' since it isn't a known property of 'input'. (" ][(ngModel)]="SearchQuery" class="form-control form-control-lg" placeholder="Search iTunes..." value="): ng:///AppModule/ContentComponent.html@8:31 – Sole Nov 17 '19 at 03:29
  • https://stackoverflow.com/questions/43298011/angular-error-cant-bind-to-ngmodel-since-it-isnt-a-known-property-of-inpu/43298039#43298039 – Sajeetharan Nov 17 '19 at 03:30
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/202500/discussion-between-sole-and-sajeetharan). – Sole Nov 17 '19 at 03:36
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;
})
}
}
Himanshu Sharma
  • 560
  • 3
  • 12