我試圖了解如何從 Observable 型別的物件中提取資料,經過一些研究,我主要依靠兩種解決方案。subscribe(這在我的情況下不起作用或我用得不好),或不再存在的地圖。我指定我使用嵌套。
這里我的目標是能夠直接回傳填充了答案資料的變數this.followers
這是我的代碼。
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { GithubFollower } from './../../../../shared/github.models'
@Injectable()
export class GithubService {
private followers: GithubFollower[]
constructor(private httpService: HttpService) {}
getFollowers(id: string): GithubFollower[] {
this.httpService.get<GithubFollower[]>(`https://api.github.com/users/${id}/followers`)
.subscribe(data => {
this.followers = data.data // this.followers = my data
console.log(this.followers); // print my data
});
console.log("here", this.followers); // print "here undefined"
return this.followers; // this.followers = []
}
}
如何從 Observable 中提取資料?
uj5u.com熱心網友回復:
盡管.toPromise在 RxJs 8 中已棄用,但您可以在 rxjs 7 及以下版本中使用它。所以試試這個:
async getFollowers(id: string): GithubFollower[] {
const githubData = await this.httpService.get<GithubFollower[]>(`https://api.github.com/users/${id}/followers`).toPromise()
this.followers = githubData.data
return this.followers; // this.followers now returns the followers instead of undefined
}
uj5u.com熱心網友回復:
按照我昨天晚上的問題,我找到了兩個解決方案。第一個是使用該pipe函式(即使我不太了解它的作用,我很樂意在這篇文章的評論中進行解釋),它為我們提供了以下資訊:
getFollowers(id: string): Observable<DashBoardResponse> {
return this.httpService
.get<GithubFollower[]>(`https://api.github.com/users/${id}/followers`)
.pipe(
map(res => {
const response: DashBoardResponse = {
code: res.data !== [] ? 200 : 400,
message: res.data !== [] ? 'success' : 'Possible bad id',
response: res.data
}
return response;
})
)
}
然后 nest 能夠在將回應發送回客戶端之前從控制器中提取回應。
我可以擁有的第二個解決方案是對 @KZoep 進行了一些修改,因為在當前版本的 nest 中,不可能在async/await不回傳Promise. 這是代碼:這里我的目標是能夠直接回傳填充了答案資料的變數this.followers
async getFollowers(id: string): Promise<DashBoardResponse> {
this.followers = await (await this.httpService.get<GithubFollower[]>(`https://api.github.com/users/${id}/followers`).toPromise()).data
return new Promise((resolve, reject: (reason?: DashBoardResponse) => void) => {
if (this.followers !== []) {
resolve({
code: 200,
message: 'success',
response: this.followers
});
} else {
reject({
code: 400,
message: 'Possible bad id',
response: []
})
}
})
}
無論如何,感謝您的幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/362692.html
下一篇:影像在調整CSS大小時下移
