如何在Angular Observable中将多个Pipe组合为数组并动态调用
I see you're trying to refactor your Observable pipe logic to use a dynamic array of pipes, but hitting a TypeError: Object(...)(...) is not a function when passing the array directly. Let's break down why this happens and how to fix it.
The Problem
Your initial approach of passing the array directly to pipe() doesn't work because RxJS's pipe() method accepts a variable number of operator functions (rest parameters), not a single array containing those functions. When you pass the array as-is, it's treated as one argument that isn't a valid operator function—hence the error you're seeing.
The Solution
Use the ES6 spread operator (...) to expand your array of pipes into individual arguments that pipe() expects. This tells JavaScript to unpack each element of the array as a separate parameter, which matches how pipe() is designed to work.
Updated Code Example
Here's how to adjust your code to implement this fix:
getOrders(filters: any, page: any = 1, orderBy: string = 'deliver_on', sort: string = 'asc') { // Define your individual filter operators const opCityFilter = filter((obj: any) => obj.payload.order.op_city_id === 1); const storeRefFilter = filter((obj: any) => obj.payload.order.store.ref.match(/^Your.*/)); const statusFilter = filter((obj: any) => ['assign_request', 'accepted', 'in_store', 'en_route_to_client', 'arrived', 'canceled'].indexOf(obj.payload.order.status) !== -1); // Collect operators into an array for dynamic configuration const pipes = [opCityFilter, storeRefFilter, statusFilter]; return Observable.create((observer: Observer<any>) => { this.socket.on('private-order.status.changed.1:order.status', (obj: any) => { observer.next(obj); }); }).pipe(...pipes); // Use spread operator to expand the array into individual arguments }
Bonus: Flexible Dynamic Configuration
Since you're aiming for dynamic setup, you can easily add/remove pipes based on conditions before passing them to pipe(). For example:
const pipes = []; // Conditionally add filters based on input parameters if (filters.restrictToOpCity1) { pipes.push(opCityFilter); } pipes.push(storeRefFilter); // Adjust status filter based on whether canceled orders should be included if (!filters.includeCanceled) { pipes.push(filter((obj: any) => obj.payload.order.status !== 'canceled')); } else { pipes.push(statusFilter); } // Apply all dynamically selected pipes return yourObservable.pipe(...pipes);
This makes your pipe logic far more flexible and maintainable as your requirements change.
内容的提问来源于stack exchange,提问作者Garine Pondikian

