用例:调用服务(movies.service.ts),该服务将检查数据是否在cookie中,以及是否将cookie数据作为JSON返回。如果它不是,则调用http.get()端点并将数据放入cookie中并返回。
我相信我的代码很好吗?但是,当我从组件(movies.component.ts)调用此服务方法时,它返回' undefined'。这是一个时间问题。在完成console.log之前,我需要能够告诉它什么时候完成?
以下代码:
movies.service.ts
DynamicRoutes::reload
movies.component.ts
GetGenres() {
//Check cookie first
this.cookieService.delete('movie-genres');
var cookieExists = this.cookieService.check('movie-genres');
console.log(cookieExists);
//if no cookie exists, call endpoint and set cookie
if(!cookieExists) {
//
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
let url = 'https://api.themoviedb.org/3/genre/movie/list?language=en-US&api_key=' + this.apiKeyV3;
let dto = { };
//All endpoints currently accept only HTTP GET requests.
var response = this.http.get(url, options)
.map(this.extractData)
.catch(this.handleError);
response
.subscribe(
res => {
//next
//this.genres = res.genres;
console.log("next");
this.cookieService.set('movie-genres', JSON.stringify(res.genres));
},
error => {
var msg = { "Type": "Failure", "Message": <any>error };
},
() => {
//complete
console.log('completed');
return this.cookieService.get('movie-genres');
}
);
}
else {
console.log('have cookie');
var cookie = this.cookieService.get('movie-genres');
return cookie;
}
}
答案 0 :(得分:1)
我将解释部分代码以显示问题:
if(!cookieExists) {
var response = // start making an async http request
response.subscribe(
// asynchronously handle the result of that request
);
}
请注意,这里没有“返回”。你确实在异步位内有一个返回,但是在你的函数中没有运行,所以它不计算。这就是你得到“未定义”的原因。您要做的是在return response
之后添加response.subscribe()
,然后此函数的调用者可以执行this.moviesService.GetGenres().subscribe( () => { ... }
。