我是 angular 和 Observables 的新手。我的 Rest API 總是回傳自定義回應型別
export class CustomApiResponse {
isSucess: boolean | undefined; // denotes whether request was sucess
statusCode: number | undefined; // custom status codes from webapi
error: string | undefined; // error message in case of error
value: any; //data which may be array of object or single object
}
我為所有 httprequest 提供通用服務
export class HttpHelperService {
BaseUrl:String="mydominurl/api";
constructor( private httpclient :HttpClient) { }
GetData(url:string) : Observable<CustomApiResponse>{
return this.httpclient.get<CustomApiResponse>(this.BaseUrl url);
}
}
現在我需要呼叫這個 httphelper 并使用我的服務從回應中提取資料作為可觀察的,如下所示(我無法弄清楚)
export class CategoryService {
url:String="/api_category";
constructor( private httphelper :HttpHelperService) { }
getCategories(url:string) : Observable<Category[]>{
this.httphelper.GetData(url).subscribe(val=>{
if(val.isSucess){
return val.value; //How to do this
}} ); }
}
請建議我如何重寫上述方法,以便我可以從我的組件中呼叫上述服務,如下所示
export class CategoryListComponent implements OnInit {
Items: Observable< Category[]> | undefined;
url:string="/Api_category";
constructor( private catservice :CategoryService) {
}
ngOnInit(): void {
this.catservice.getCategories(this.url).subscribe(val=> this.Items=val);
}
}
uj5u.com熱心網友回復:
我認為您要做的是在從 HttpHelper 獲得回復后修改提供給 CategoryListComponent 的值。
這可以使用map運算子來完成,如下所示:
export class CategoryService {
url:String="/api_category";
constructor( private httphelper :HttpHelperService) { }
getCategories(url:string) : Observable<Category[]>{
return this.httphelper.GetData(url).pipe(map((val) => val.isSuccess ? val.value : []));
}
}
這將回傳一個新的 observable,它將回應的值從 GetData 更改為其他值(在這種情況下,如果 val.isSuccess 為真,則為 val.value,否則為空串列)。
然后你的組件將要訂閱,它會正常作業。
始終嘗試訂閱 observables 作為一長串 observables 的最后一步。這將需要大量的 RxJS 學習,但這是正確的方法,理想情況下,您將讓您的組件訂閱 observable,其余的中間服務將映射、過濾、轉換或組合資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/352515.html
標籤:有角的 rxjs 可观察的 角-httpclient rxjs-observables
