使用 rxjs 在立面架构中观察到未定义

observable undefinded in facade architeture with rxjs

(根据 gunnar 的建议,我正在编辑我的问题) @Gunnar.B

连接服务 api

@Injectable({
  providedIn: 'root'
})
export class ConsolidadoApi {
  constructor(private http: HttpClient) { }
  getInvestiments(search?: any): Observable<any> {
    return this.http.get<any>(`${environment.basePosicaoConsolidada}`);
  }
}

此服务(层)为表示层(组件)中的组件公开状态流和接口

@Injectable({
    providedIn: 'root'
})
export class CoreService {

    constructor(private api: ConsolidadoApi, private state: StateService) { }

    public getInvestments$(): Observable<any> {
        return this.state.getInvestiments$()
    }

    public loadInvestments() {
        return this.api.getInvestiments()
        .pipe(
            tap(investPortifolio => this.state.setInvestments(investPortifolio))
        );
    }
}

此服务负责将转到组件的逻辑

@Injectable({
  providedIn: 'root'
})
export class StateService {

  private investments$ = new BehaviorSubject<any>(null);

  public getInvestiments$() {
    return this.investments$.asObservable()
  }

  public setInvestments(investPortifolio){
    this.investments$.next(investPortifolio)
  }
}

但是在我的html中没有出现来自api的数据。

menu.component.ts

export class MenuComponent implements OnInit {
  
  investments$: Observable<any>;

  constructor( private coreService : CoreService ) {
    this.investments$ = this.coreService.getInvestments$()
   }


  ngOnInit(): void {
    this.coreService.loadInvestments();
    console.log(this.coreService.loadInvestments())
  }

}

menu.component.html

    <div>
        test
    </div>

    <div *ngFor="let investimentPortifolio of investments$ | async;">
        {{investimentPortifolio | json}}
    </div>

listInvestments 方法正在执行异步 API 调用。所以基本上投资 属性 在你调用 forEach 时仍然是未定义的。

您想在从服务器加载数据之后而不是之前循环 investments 数组。

一种方法是确保您在订阅的 next() 回调中,并且您确定您拥有执行操作所需的数据。

核心服务 class 变为:

@Injectable({
    providedIn: 'root'
})
export class CoreService {
    public investments: any;
    constructor(private api: ConsolidadoApi, private state: StateService) {}

    public createMenu(){
      this.api.getInvestments()
            .subscribe(response => {
                this.investments = response;
                this.investments.forEach(element => {
                  console.log(element)
                });
            })
       
    }
}

问题编辑更新

在 ngOnInit 中,您调用了 loadInvestments(),returns 是一个可观察对象。并且 observable 是惰性的,这意味着如果你不调用它们订阅什么都不会发生。

你需要做的是改变这一行:

this.coreService.loadInvestments();

this.coreService.loadInvestments().subscribe();