我正在向后端发出 HTTP 请求并在我的主应用程序服务中获取数据。我通过在我的联系人服务中映射它并在我的联系人组件中订阅它来扩展该 observable。但是,我在这样做时遇到了问题。数据打印为未定义。
这是我的代码:
<块引用>app.service.ts
postHTTPRequest(url: string, tokenValue: string) : Observable<any>
{
return this.http.post(this.baseURL + url, {token: tokenValue});
}
<块引用>
contacts.service.ts
getData() : Observable<any>
{
return this.appService.postHTTPRequest(this.contactsURL, this.tokenValue).pipe(map(response => {
console.log("Printing in contacts service " + response);
}))
}
<块引用>
contacts.component.ts
getData()
{
this.contactsService.getData().subscribe(response => {
console.log("Printing in the component " + response);
})
}
我在控制台 Printing in the component undefined
上得到了这个。服务部分打印完全正常。帮助。谢谢!
答案 0 :(得分:1)
在您的 contacts.service.ts
中,您 map
对 undefined
的响应,因为没有实际的返回值。
改自
getData() : Observable<any>
{
return this.appService.postHTTPRequest(this.contactsURL, this.tokenValue).pipe(map(response => {
console.log("Printing in contacts service " + response);
}))
}
到
getData() : Observable<any>
{
return this.appService.postHTTPRequest(this.contactsURL, this.tokenValue).pipe(map(response => {
console.log("Printing in contacts service " + response);
return response;
}))
}
答案 1 :(得分:1)
当您使用 pipe
和 map
时,它必须在您的地图函数中返回值,因此您需要像下面那样更新您的代码。
getData() : Observable<any>
{
return this.appService.postHTTPRequest(this.contactsURL, this.tokenValue).pipe(map(response => {
console.log("Printing in contacts service " + response);
return response;
}))
}
返回响应后,您将获得与订阅方法相同的数据。
如果您没有更改您的响应数据而只是简单地返回它,那么您可以简单地编写没有 pipe
和 map
函数的 return。
示例:
getData() : Observable<any>
{
return this.appService.postHTTPRequest(this.contactsURL, this.tokenValue);
}
编辑:关于代码优化的另一个建议,您可以省略 contacts.service.ts
,也可以直接在联系服务中调用您的 API,而无需 app.service.ts
依赖。