包装Observable方法

时间:2016-05-26 06:40:47

标签: visual-studio-2015 angular rxjs typescript1.8

似乎无法围绕链接/包裹可观察物。我在Visual Studio 2015中的Typescript中使用Angular2 rc1和RxJ。

我在ProductService类中有一个servicemethod'saveProduct':

public saveProduct(product: Product): Observable<string> {
    let options = new RequestOptions({ headers: new Headers({ 'Content-Type': 'application/json' }) });
    return this.http.post(this.config.apiUrl + '/product', JSON.stringify(product), options).map(this.extractData).catch(this.handleError);
}

我在angular2组件中使用它:

public save() {
    this.productService.saveProduct(this.product).subscribe(
        result => this.productSaveExecuted(result),
        error => this.handleError(error)
    );
}

组件被包装在一个模态对话框中,如果我在调用组件的save方法后关闭对话框,则会在保存操作完成之前关闭对话框。所以,我希望组件的保存功能也返回一个Observable,因为组件被包装在一个模式div中,我想在成功保存后关闭。我该如何做到这一点?

2 个答案:

答案 0 :(得分:1)

这样的事情:

import com.activeandroid.Model;

public save(): Rx.Observable<{ success: boolean }> { return this.productService .saveProduct(this.product) .select(result => { this.productSaveExecuted(result); return { success: true }; }) .catch(error => { this.handleError(error); return Rx.Observable.return({ success: false }); }); } 方法将返回一个observable,订阅时会尝试保存该产品。

订阅save方法:

save

我认为这就是你想要的......你的问题并不完全清楚。

答案 1 :(得分:0)

可观察者可以被包裹起来&#39;在另一个像这样的观察中:

public save(): Observable<{}> {
    console.log("productdetails.component save was called");

    return Observable.create(observer => {
        this.productService.saveProduct(this.product).subscribe(
            result => this.productSaveExecuted(result),
            error => this.handleError(error)
        );
        observer.next(),
        function (err) {
            console.log('Error: ' + err);
        },
        //call complete if you want to close this stream (like a promise)
        observer.complete();
    });

}

另一种解决方案是从productService订阅生成的Observable,并从.toPromise()方法返回promise。

谢谢Nypan支持我的学习过程:)