2016-11-11 52 views
1

我試過這個刪除operations產品ID等於myProdID。 它刪除了整個操作分支,而不僅僅是等於查詢結果的分支。如何在一個步驟中刪除列表查詢的結果?

this.af.database.list('operations', { 
     query: { 
      orderByChild: 'products/productID', 
      equalTo: myProdID 
     } 
     }).remove(); 

我應該使用什麼才能在一行代碼中完成而不是運行循環來刪除每個項目? .map?

回答

2

它比一行代碼多一點,但你可以這樣做:

deleteOperations(productID: any): Observable<any> { 

    return this.af.database.list('operations', { 
    query: { 
     orderByChild: 'products/productID', 
     equalTo: productID 
    } 
    }) 

    // AngularFire2 list/object observables don't complete - they re-emit if 
    // the database changes - so use the first operator to ensure it completes 
    // and ignores subsequent database changes. 

    .first() 

    // Use Array.prototype.reduce to create an object containing the keys to 
    // be removed and use the FirebaseObjectObservable's update method to 
    // remove them. 

    .mergeMap((ops) => this.af.database.object('operations').update(
    ops.reduce((acc, op) => { acc[op.$key] = null; return acc; }, {}) 
)); 
} 

上述函數將返回觀察到的和刪除會當呼叫者訂閱它來執行。

如果你希望有函數返回一個承諾,你可以做這樣的事情:

deleteOperations(productID: any): Promise<any> { 

    return this.af.database.list('operations', { 
    query: { 
     orderByChild: 'products/productID', 
     equalTo: productID 
    } 
    }) 

    // AngularFire2 list/object observables don't complete - they re-emit if 
    // the database changes - so use the first operator to ensure it completes 
    // and ignores subsequent database changes. 

    .first() 

    // Convert the observable to a promise when that will resolve when the 
    // observable completes. 

    .toPromise() 

    // Use Array.prototype.reduce to create an object containing the keys to 
    // be removed and use the FirebaseObjectObservable's update method to 
    // remove them. 

    .then((ops) => this.af.database.object('operations').update(
    ops.reduce((acc, op) => { acc[op.$key] = null; return acc; }, {}) 
)); 
} 
+0

它沒有工作。我查看了更多關於mergeMap的內容,[https://gist.github.com/btroncone/d6cf141d6f2c00dc6b35#mergemap](RxJS 5 Operators By Example)有一個例子,但我看不出與你有什麼不同。 – Bogac

+0

'mergeMap'用於在'update'返回的promise被解析時完成observable。它以什麼方式不起作用? – cartant

+0

對不起,我訂閱了它。我對RxJS的東西不太滿意。有什麼辦法可以回報承諾嗎?我打算把它放在一個服務函數中,所以當它被調用時它會返回一個promise,並在調用組件中得到解決。 – Bogac

0

你可以像這樣執行一個更新:

ref.update({ 
    '/operations/products/foo': null, 
    '/operations/products/bar': null 
}); 

這將批量,同時保持所有其他的孩子從不變刪除ref/operations/products的foo和酒吧的孩子。

但我想你仍然需要做一些循環來確定哪些路徑要更新。

相關問題