typescript 使用 Rxjs 6 在 Angular 6 中返回一个空/空的 Observable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51434236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:32:23  来源:igfitidea点击:

Return a null/empty Observable in Angular 6 with Rxjs 6

typescriptrxjsangular6rxjs6

提问by KevDing

I am working on Angular 6 with Rxjs 6while I have a question regarding returning a null/empty Observable if response failed or has exception, Here is my assumption, my remote api will return an object of IOptionResponse, it contains a message string which could be indicated like 'SUCCESS' or 'FAILED', it also contains a model which is an array of 'IOption' object

我正在使用 Rxjs 6处理Angular 6,同时我有一个关于如果响应失败或有异常返回空/空 Observable 的问题,这是我的假设,我的远程 api 将返回一个IOptionResponse对象,它包含一个消息字符串,可以被指示为“成功”或“失败”,它还包含一个模型,它是一个“IOption”对象数组

export interface IOptionResponse {
    message: string;
    model: IOption[];
}

Here is my service method name, it will return a Observable of IOption array which is the "model" of my remote API result

这是我的服务方法名称,它将返回一个 IOption 数组的 Observable,它是我的远程 API 结果的“模型”

loadIOptionMembersRelationship(): Observable<IOption[]> {
    return this.httpClient.get<IOptionResponse>('${environment.apiUrl}/api/member/XXX')
        .map(
            (response) => {
                console.log(response);
                // if response.message is success, return IOption[] model
                if (response.message == responseMessage.Success) {
                    return response.model;
                }
                else {
                    // return Observable.empty<IOption[]>(); failed
                    // return new Observable.empty<IOption[]>(); failed
                    // return new EmptyObservable<IOption[]>(); failed
                    // return new Observable<IOption[]>.from([]); failed
                    // Otherwise return a NULL/EMPTY Observable
                    //What should be the correct way to implement here???
                }
            }
        );
}

I've read the post herewhich is similar, however I tried all the possible solution and they do not work, I am not sure if it's because that posted solutions are out of date or maybe some method changed in rxjs 6 or maybe it's a typescript issue...

我已经在这里阅读了类似的帖子,但是我尝试了所有可能的解决方案,但它们都不起作用,我不确定是因为发布的解决方案已过时,还是 rxjs 6 中的某些方法已更改,或者它可能是一个打字稿问题...

回答by Pooshon Banerjee

If you want to return an empty Observable array while using Rxjs6, you need to...

如果你想在使用 Rxjs6 时返回一个空的 Observable 数组,你需要...

import { of } from 'rxjs';

Then where you want to return your empty Observable array of <IOption[]> type ...

然后你想在哪里返回 <IOption[]> 类型的空 Observable 数组......

return of<IOption[]>([]);

回答by CozyAzure

Do you care about FAILEDresults? If you do not (which is quite true since you want to emit an empty Obersavble), you can just simply filter it. Then you do not need to explicitly emit an empty Observable:

你在乎FAILED结果吗?如果你不这样做(这是真的,因为你想发出一个空的 Obersavble),你可以简单地过滤它。那么你不需要显式地发出一个空的 Observable:

 loadIOptionMembersRelationship(): Observable<IOption[]> {
    return this.httpClient.get<IOptionResponse>('${environment.apiUrl}/api/member/XXX')
        .filter(response => response.message === responseMessage.Success) //only emit those response whose message is SUCCESS
        .map(response => response.model);
}

Explicitly returning an emptyObservable will terminate the stream, which may or may not be what you want depending on your implementation.

显式返回emptyObservable 将终止流,这可能是您想要的,也可能不是您想要的,具体取决于您的实现。

回答by Mihail

All solution from the post you mention will not trigger "next" callback and your workflow will not work. Just simply do

您提到的帖子中的所有解决方案都不会触发“下一个”回调,并且您的工作流程将不起作用。只是简单地做

return;

But in this case you will loose error information. I think best way to do it is following

但在这种情况下,您将丢失错误信息。我认为最好的方法是遵循

throw new Error("Failed to get the model...");

回答by SirDieter

When using map()you transform the data the new observable emits based on its source observable. The problem you have is that you try return an emptyObservable although your Observable should return a value of type IOptionsResponse. So your Observable is based of your code an Observable<IOptionsResponse | Observable<IOptionsResponse>>. You could just return null or undefined in your else.

使用时,map()您可以转换数据,新的 observable 根据其源 observable 发出。您遇到的问题是您尝试返回一个emptyObservable,尽管您的 Observable 应该返回一个 type 值IOptionsResponse。所以你的 Observable 是基于你的代码和Observable<IOptionsResponse | Observable<IOptionsResponse>>. 您可以在 else 中返回 null 或 undefined 。