包装 Observable 方法

Wrapping Observable methods

我似乎无法理解链接/包装可观察对象。我在 Visual Studio 2015 年的 Typescript 中使用 Angular2 rc1 和 RxJs。

我在 ProductService class 中有一个服务方法 '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)
    );
}

组件包含在模态对话框中 wi 如果我在调用组件的保存方法后关闭对话框,对话框将在保存操作完成之前关闭。所以,我希望组件的保存功能也 return 一个 Observable,因为组件被包装在模态 div 我想关闭 after[=21] =] 成功保存。我该如何实现?

像这样:

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 });
        });
}

save 方法将 return 订阅时将尝试保存产品的可观察对象。

正在订阅 save 方法:

save()
    .subscribe(result => {
        if(result.sucess)
            // everything went well
        else 
            // something went wrong
    })

我想这就是你想要的..你的问题不是很清楚

Observables 可以 'wrapped' 在另一个 observable 中,像这样:

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 和 return 来自 .toPromise() 方法的承诺。

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