簡體   English   中英

角度7:如何從嵌套響應中正確地訪問this.http.get?

[英]Angular 7: How to properly this.http.get from a nested response?

我正在做Angular 7教程,想知道如果它們不在頂層而是嵌套的 ,如何正確地請求項目列表

頂層(作品)

[
  { id: 123, name: 'Name 123'},
  { id: 124, name: 'Name 124'},
  // ...
]

嵌套(無效)

{
  message: 'x items found.',
  data: [
    { id: 123, name: 'Name 123'},
    { id: 124, name: 'Name 124'},
    // ...
  ]
}

服務

// ...
@Injectable({ providedIn: 'root' })
export class ItemService {
  private apiUrl = 'api/items'; // items are in .data

  constructor(private http: HttpClient) {}

  getItems (): Observable<Item[]> {      
    // Here is the problem:
    return this.http.get<Item[]>(this.apiUrl, {
      pathToItems: 'data' // <- Pseudocode
    });
  }
}

零件

// ...
this.itemService.getItems()
  .subscribe(items => this.items = items);

我可以在服務中使用subscribe()並返回.data的內容,但我認為應該有一個更簡單的解決方案。 我需要保留返回類型( Item數組)。

任何想法?

提前致謝!

您可以使用mapfilter之類的RxJs過濾 這是使用RxJ(可觀察到的)的優點之一。 您可以在將數據傳遞到組件之前對其進行過濾。

一個例子:

 return this.http.get(ITEMS_URL).pipe( filter(response => response.filter(data => data.message === "SUCCEEDED")), map(response => response.map(data => data.items)) ); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM