[英]Type Undefined is not assignable to type [Film]
I am learning how to make http request in angular using service and here is my code: 我正在学习如何使用服务以角度发出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);
}
);
}
}
When I launch the app I get this error, ERROR in src/app/services/apicall.service.ts(15,5): error TS2322: Type 'undefined[]' is not assignable to type '[Film]'. 启动应用程序时,出现此错误, src / app / services / apicall.service.ts(15,5)中的错误:错误TS2322:类型'undefined []'无法分配给类型'[Film]'。 Property '0' is missing in type 'undefined[]'.
类型'undefined []'中缺少属性'0'。
And in the console I have this error: Cannot read property 'push' of undefined 在控制台中,我出现以下错误: 无法读取未定义的属性“ push”
I don't understand why, i tried several was to declare the foundFilms array but I cannot make it work. 我不明白为什么,我尝试了几次是声明foundFilms数组,但是我无法使其工作。
I hope someone can help 我希望有人能帮帮忙
Thanks Alessandro 谢谢亚历山德罗
声明数组时,需要对其进行初始化。
foundFilms: Film[] = [];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.