【发布时间】:2018-02-27 04:29:56
【问题描述】:
我查看了其他解决方案,因为有与我类似的问题,但我找不到答案。我不确定在这里做什么,我尝试了多种不同的方法。我对 Angular 还是很陌生。
错误:
books-search.component.ts:13 Uncaught TypeError: Cannot read property 'testService' of undefined
更新:
我相信我可以在那里测试该方法,但我错了。移动方法调用后,我遇到了一个新错误。
新错误:
compiler.js:19550 未捕获错误:提供程序解析错误: 无法实例化循环依赖! BooksService ("[ERROR ->]"): 在 NgModule AppModule 中的 ./AppModule@-1:-1
更新:
已修复错误,谢谢。
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 { }
【问题讨论】:
-
将您的
function替换为arrow function。$.getJSON(googleAPI, (response) => this.service.testService()); -
为什么你的
this.service.testService()不在 ngOnInit 功能块中?
标签: angular typescript