[英]Angular: Data undefined while subscribing to the observable
我正在向后端發出 HTTP 請求並在我的主應用程序服務中獲取數據。 我通過在我的聯系人服務中映射它並在我的聯系人組件中訂閱它來擴展該 observable。 但是,我在這樣做時遇到了問題。 數據打印為未定義。
這是我的代碼:
應用服務.ts
postHTTPRequest(url: string, tokenValue: string) : Observable<any>
{
return this.http.post(this.baseURL + url, {token: tokenValue});
}
聯系人.service.ts
getData() : Observable<any>
{
return this.appService.postHTTPRequest(this.contactsURL, this.tokenValue).pipe(map(response => {
console.log("Printing in contacts service " + response);
}))
}
contact.component.ts
getData()
{
this.contactsService.getData().subscribe(response => {
console.log("Printing in the component " + response);
})
}
我Printing in the component undefined
控制台Printing in the component undefined
上得到了這個。 服務部分打印完全正常。 幫助。 謝謝!
在您的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;
}))
}
當您使用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
函數的返回。
樣本:
getData() : Observable<any>
{
return this.appService.postHTTPRequest(this.contactsURL, this.tokenValue);
}
編輯:關於代碼優化的另一個建議,您可以省略contacts.service.ts
或者您可以在沒有app.service.ts
依賴關系的情況下直接在contact 服務中調用您的API。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.