我正在学习如何使用角度使用服务进行http请求,这是我的代码:
export class ApiCallService {
// DECLARATIONS:
tmdb_api_key = '*******'; // personal api key to access the TMDB API
posterBaseAddress = 'https://image.tmdb.org/t/p/w300'; // base
address of the TMDB poster link, to add film specific path
// SEARCH PARAMETERS
requestPages: number; // get the number of pages for the request so is possible to load all the films (request is 1 page at time)
pageToLoad = 1; // number of page to load, start with 1
baseLanguage = 'en-US'; // return film in english, search can be done in local language but return english titles
foundFilms: [Film] = [];
constructor(private http: Http) {}
// TODO: GET method to search for film
getFilmsByTitle(filmTitle: string, page: number) {
// if the search has only 1 page will be 1 otherwise will load the films on the respective page
this.pageToLoad = page;
return this.http.get('https://api.themoviedb.org/3/search/movie?' +
'api_key=*******$' +
'&language=' + this.baseLanguage +
'&query=' + filmTitle +
'&page=' + this.pageToLoad +
'&include_adult=false')
.map(
(response: Response) => {
const films = response.json();
for (const film of films['results']) {
const singleFilm = new Film(film.title, film.overview, film.release_date, film.poster_path, film.genre_ids);
this.foundFilms.push(singleFilm);
}
this.requestPages = films.total_pages;
return this.foundFilms;
}
);
}
}
export class AppComponent implements OnInit {
constructor(private apiCallService: ApiCallService) {}
ngOnInit() {
this.apiCallService.getFilmsByTitle('Harry', 1).subscribe(
(films: [any]) => {
console.log(films);
}
);
}
}
当我启动应用程序时,我收到此错误,在src / app / services / apicall.service.ts(15,5)中出现错误:错误TS2322:类型'undefined []'不能分配给'[Film]'类型。 'undefined []'类型中缺少属性'0'。
在控制台中我有这个错误:无法读取未定义的属性'push'
我不明白为什么,我尝试了几个是声明findFilms数组,但我不能使它工作。
我希望有人能帮帮忙
谢谢亚历山德罗
您需要在声明时初始化数组。
foundFilms: Film[] = [];