[英]How to pipe / map an Observable in Angular
嵌套對象顯示為 [object Object],所以我試圖通過管道和地圖投射它,但我沒有得到任何地方。 我已經嘗試將模型作為類和接口,但沒有幫助。 有人能告訴我我做錯了什么嗎? 謝謝。
功能:
getClients(customerId: number): Observable<Client[]> {
let clientUrl = 'SOME_URL';
return this.http.get<Client[]>(clientUrl)
.pipe(map(client: Client) => client.address as Address);
}
型號:
import { Address } from './address.model';
export class Client{
id: number;
name: string;
accountNumber: string;
addressId: number;
phoneNumber: string;
address: Address;
}
export class Address{
id: number;
name: string;
addressLine1: string;
addressLine2: string;
city: string;
postalCode: string;
}
我收到錯誤消息:“地址”類型的錯誤 TS2345 (TS) 參數不可分配給“OperatorFunction<{}, Client[]>”類型的參數。
1) 從 getClients() 方法中刪除管道部分
2) 在訂閱 getClients() 或創建另一個方法之前執行管道映射,該方法僅執行從 getClients() 返回的 observable 的管道部分
mapToAddress(): Observable<Address[]> {
this.getClients.pipe(
map((clients: Client[]) => clients.map(client => client.address))
)
}
理解這一點很重要:當您在 .pipe() 中調用 .map() 方法時,在這種情況下您不會獲得單個客戶端,而是獲得整個客戶端數組,並推送到 Observable。 因為您映射了存儲在 Observable 中的值 - 類型的值:<Client[]>。
您的管道映射將在某些 Observable 上工作,它發出一個 <Client> 類型的客戶端,而不是一個數組。
問題在這里:
getClients(customerId: number): Observable<Client[]> {
您請求函數以 observable(客戶端數組)的形式返回,但實際上您返回的是地址的 Observable。
.pipe(map(client: Client) => client.address as Address);
這就是該函數拋出此錯誤的原因。 將Observable<Client[]>
替換為Observable<Address[]>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.