I've browsed through various solutions as there were similar queries like mine, but unfortunately, I couldn't find a suitable answer. Feeling quite lost here, I've experimented with different methods since I'm fairly new to Angular.
ERROR:
books-search.component.ts:13 Uncaught TypeError: Cannot read property 'testService' of undefined
UPDATE:
I mistakenly assumed I could test the method there and encountered a new error after relocating the method call.
NEW ERROR:
compiler.js:19550 Uncaught Error: Provider parse errors: Cannot instantiate cyclic dependency! BooksService ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
UPDATE:
The error has been rectified, thank you.
books-search.component.ts
import { Component, OnInit} from '@angular/core';
import { BooksService } from '../services/books.service';
declare var jquery:any;
declare var $ :any;
@Component({
selector: 'app-books-search',
templateUrl: './books-search.component.html',
styleUrls: ['./books-search.component.css']
})
export class BooksSearchComponent implements OnInit {
constructor(private service:BooksService){};
ngOnInit(){
//moved here after second edit
this.service.testService();}
searchBook(bookTitle:string){
var searchTerm = '';
var books = [];
//initial api url
var googleAPI = "https://www.googleapis.com/books/v1/volumes?q=";
//grabbing our search term
searchTerm = bookTitle;
//replacing spaces with +
searchTerm.toString();
searchTerm = searchTerm.replace(/ /g,"+");
//adding our searchterm to our api
googleAPI += searchTerm;
// gets a json object from google books api
$.getJSON(googleAPI, function(response){
this.service.testService();
});
}
}
books.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class BooksService {
constructor(private service: BooksService){}
public books = [];
testService(){
console.log('service test success!');
}
setData(data){
this.books = data;
console.log('data set : ' + this.books);
}
getData(){
return this.books;
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BooksService } from './services/books.service';
import { AppComponent } from './app.component';
import { BooksSearchResultComponent } from './books-search-result/books-search-result.component';
import { BookshelfComponent } from './bookshelf/bookshelf.component';
import { BooksSearchComponent } from './books-search/books-search.component';
@NgModule({
declarations: [
AppComponent,
BooksSearchResultComponent,
BookshelfComponent,
BooksSearchComponent
],
imports: [BrowserModule],
providers: [BooksService],
bootstrap: [AppComponent]
})
export class AppModule { }