我从事的一个项目基本上是通过一个名为ServiceHandler的中介类调用服务方法.在该组件中,Result变量的控制台输出为undefined. 有没有解决这个问题的办法?

Component

this.entityServiceHandler.saveEntityWithCondition(entity).subscribe(data => { this.result = data});

console.log(this.result);

ServiceHandler

public saveEntityWithCondition(entity): Observable<Entity>{
    var subject = new Subject<any>();

    this.subscriptions.push(
      forkJoin({
        conditionTrue: this.entityService.isConditionTrue(entity.property)
      }).subscribe(({ conditionTrue }) => {
   
        if (conditionTrue) {
        
            this.entityService.save(entity).subscribe(
              (response: Entity) => {
                subject.next(response);
                
              },
              (errorResponse: HttpErrorResponse) => {
                
              }
            )
        }
      },
      err => {},
      () => {
      }));

    return subject.asObservable();

}

Service

public save(item: Entity) : Observable<Entity>{

  public save(item: Entity): Observable<Entity> {   
      return this.httpClient.post<Entity>(`path`, item).pipe(catchError((err) => this.handleAndThrowError(err)));
    }  
}

推荐答案

欢迎使用StackOverflow.您看到undefined的原因是您混合了同步和异步代码,这通常会导致问题.只要把console.log移到subscribe里面就可以了.

// Asynchronous code - takes some time to finalize
this.entityServiceHandler.saveEntityWithCondition(entity).subscribe(data => {
  this.result = data;
  console.log(this.resul) // This'll be shown
});

// Synchronous code - happens just after calling previous, doesn't wait for it
// to finish. This means, result is undefined
console.log(this.result);

EDIT: 我冒昧地简化了您的代码.你在做很多不必要的事情,比如只有一个观察点就有forkJoin件.或者将订阅推送到一个数组,可能会在以后关闭它,但当您稍微引用代码时就不需要了.

import { filter, switchMap, catchError, EMPTY } from 'rxjs';

public saveEntityWithCondition(entity): Observable<Entity> {
  // No need to forkJoin, just call the function and pipe it
  return this.entityService.isConditionTrue(entity.property).pipe(
    // This makes sure that conditionTrue is true indeed
    filter(conditionTrue => conditionTrue),
    // Then use switchMap to call the entity service and perform save
    switchMap(() => this.entityService.save(entity)),
    // And use catchError to handle possible issues
    catchError(error => {
      // handle error in some way - i.e. log it or something;
      return EMPTY; 
    })
  );

}

您不再需要subject,因为您将直接返回Observable<Entity>.

您也不需要将Subscription推入数组,因为多亏了您正在使用的HttpClient和包含的switchMap操作符,当save结束时,它将自动处理unsubcribe.

Typescript相关问答推荐

返回对象的TypScript构造函数隐式地替换This的值来替换super(.)的任何调用者?

类型脚本如何将嵌套的通用类型展开为父通用类型

打字脚本中泛型和直接类型重新映射的不同行为

Typescript泛型类型:按其嵌套属性映射记录列表

如何按不能保证的功能过滤按键?

TypeScrip-将<;A、B、C和>之一转换为联合A|B|C

如何解决类型T不能用于索引类型{ A:typeof A; B:typeof B;. }'

在实现自定义主题后,Angular 不会更新视图

在Mac和Windows上运行的Web应用程序出现这种对齐差异的原因是什么?(ReactNative)

17个Angular 的延迟观察.如何在模板中转义@符号?

TS2739将接口类型变量赋值给具体变量

如何键入派生类的实例方法,以便它调用另一个实例方法?

重写返回任何

推断集合访问器类型

无法使用prisma中的事务更新记录

基于参数的 TS 返回类型

覆盖高阶组件中的 prop 时的泛型推理

如何使用动态生成的键和值定义对象的形状?

为什么在 useState 中设置 React 组件是一种不好的做法?

是否有解释为什么默认情况下在泛型类型上访问的属性不是索引访问