Javascript 从Angular 2中的服务检索对象数据
我试图从我的服务功能中检索数据,但遇到了问题。我的LandingPage组件代码(如下所示)向我的服务函数发送一个按键,然后服务函数返回一个充满数据的对象 但是我无法让服务对象返回到我的登录页面。以下是我创建服务的方式: 任务.服务.tsJavascript 从Angular 2中的服务检索对象数据,javascript,angular,Javascript,Angular,我试图从我的服务功能中检索数据,但遇到了问题。我的LandingPage组件代码(如下所示)向我的服务函数发送一个按键,然后服务函数返回一个充满数据的对象 但是我无法让服务对象返回到我的登录页面。以下是我创建服务的方式: 任务.服务.ts addKey(keystroke) { const query = "https://api.themoviedb.org/3/search/tv?api_key="; fetch(query + key + '&language=
addKey(keystroke) {
const query = "https://api.themoviedb.org/3/search/tv?api_key=";
fetch(query + key + '&language=en-US&query=' + keystroke)
.then((show) => {
show.json().then((obj) => {
// grab the items we want from the response
let resultItems = obj.results.map((show, index) => {
return {
id: show.id,
poster: show.poster_path,
rating: show.vote_average,
backdrop: show.backdrop_path,
};
});
// return our newly formed object
return { data: resultItems }
});
});
}
getKey(keystroke) {
this.TaskService.addKey(keystroke)
.subscribe(res => {
this.shows = res.data; // trying to receive service info here
});
}
以下是我尝试接收服务数据的位置,在我的:
landingpage.component.ts
addKey(keystroke) {
const query = "https://api.themoviedb.org/3/search/tv?api_key=";
fetch(query + key + '&language=en-US&query=' + keystroke)
.then((show) => {
show.json().then((obj) => {
// grab the items we want from the response
let resultItems = obj.results.map((show, index) => {
return {
id: show.id,
poster: show.poster_path,
rating: show.vote_average,
backdrop: show.backdrop_path,
};
});
// return our newly formed object
return { data: resultItems }
});
});
}
getKey(keystroke) {
this.TaskService.addKey(keystroke)
.subscribe(res => {
this.shows = res.data; // trying to receive service info here
});
}
当我尝试构建时,我在我的LandingPage组件中收到以下错误:
类型“void”上不存在属性“subscribe”
我尝试使用map而不是subscribe,但它返回类似的错误
如何将我的服务中的对象结果发送到我的组件?看起来您的服务方法中缺少了一个
返回值
,我还根据我们在评论中的讨论更改为使用http
:
addKey(击键):可观察{
常量查询=”https://api.themoviedb.org/3/search/tv?api_key=";
返回此.http.get(query+key+'&language=en-US&query='+击键)
.map(show=>{
show.json()。然后((obj)=>{
//从响应中获取我们想要的项目
让resultItems=obj.results.map((显示,索引)=>{
返回{
id:show.id,
发信人:show.poster_path,
评分:show.vote_平均分,
背景:show.background\u路径,
};
});
//返回我们新形成的对象
返回{data:resultItems}
});
});
}
如果您确实想使用fetch,您可以:
- 将方法返回签名设置为
Promise
- 在服务中使用
而不是then
map
- 在组件中使用
而不是然后
订阅
然后替换为map
(如我现在更新的答案所示)。我建议使用angular's而不是fetch,但这取决于您:)谢谢!是的,我可能不得不使用angular的http,因为即使我导入了map,我也会得到“property map不存在于'Promise'类型上”。我将尝试使用http