behaivorSubject返回null

发布于 2025-01-31 05:58:27 字数 800 浏览 3 评论 0原文

我有一个问题,我需要behaivorSubject在null时不返回该值,因为结果被第三方制造的组件抓住,如果这是无效的,它会给我带来错误。

它应该仅在从服务器中获得响应时返回相同的返回,我将代码留在此处:

  getCarList(params): Observable<CarListGrid> {
    if (this.carListSubject$ === undefined) {
      this.carListSubject$ = new BehaviorSubject<CarListGrid>(null);
      this.refetchCarList(params);
    }
    return this.carListSubject$.asObservable();
  }

  refetchCarList(gridParams) {
    const subscription = this.http.post<CarListGrid>(this.baseUrl + 'GetCar', {gridParams} ,httpOptions).pipe(map(data => this.setDefaultValuesToCar(data))).subscribe(
      (response) => {

        this.carListSubject$.next(response);
        subscription.unsubscribe();
      });
  }

是否有任何方法可以防止对象在null时响应值?否则,我该如何使用此代码来帮助我呢?

谢谢!

I have this problem, I need the behaivorSubject not to return the value when it is null, since the result is grabbed by a component made by third parties and if this is null it throws me an error.

It should return the same only when I get the response from the server, I leave my code here:

  getCarList(params): Observable<CarListGrid> {
    if (this.carListSubject$ === undefined) {
      this.carListSubject$ = new BehaviorSubject<CarListGrid>(null);
      this.refetchCarList(params);
    }
    return this.carListSubject$.asObservable();
  }

  refetchCarList(gridParams) {
    const subscription = this.http.post<CarListGrid>(this.baseUrl + 'GetCar', {gridParams} ,httpOptions).pipe(map(data => this.setDefaultValuesToCar(data))).subscribe(
      (response) => {

        this.carListSubject$.next(response);
        subscription.unsubscribe();
      });
  }

Is there any way to prevent the subject from responding with a value when it is null? Or else, how can I give this code another way to help me with that?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

永言不败 2025-02-07 05:58:27

您可以像这样过滤那些nulls:

getCarList(params): Observable<CarListGrid> {
  if (this.carListSubject$ === undefined) {
    this.carListSubject$ = new BehaviorSubject<CarListGrid>(null);
    this.refetchCarList(params);
  }
  return this.carListSubject$
    .asObservable()
    .pipe(filter((value) => value !== null));
}

You could filter those nulls out, like this:

getCarList(params): Observable<CarListGrid> {
  if (this.carListSubject$ === undefined) {
    this.carListSubject$ = new BehaviorSubject<CarListGrid>(null);
    this.refetchCarList(params);
  }
  return this.carListSubject$
    .asObservable()
    .pipe(filter((value) => value !== null));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文