首页 > 解决方案 > Angular - 将数据订阅到可观察的返回未定义

问题描述

我正在做一个 Angular 项目。但是当我将数据订阅到 observable 时遇到问题返回未定义

我有一个从 HTTP 返回数据的服务方法。

public serviceMethod(): Observable<WordList[]> {
const url = `${this.baseUrl}/wordLists`;

   return this.httpClient.get<GetResponseWordList>(url).pipe(
      map(response => response._embedded.wordLists)

   );
}

以及从服务中获取数据并将其分配给“数组”的组件方法

  componentMethod() {

  // get from the service
  this.otherService.serviceMethod().subscribe(
    data => {
      this.array = data;


    }
  );

}

我在同一个文件中有另一种使用“数组”的方法

secondMethod(){
    console.log(this.array)
}

最后,我有使用最后两种方法的主要方法。

 mainMethodMethod(){
    componentMethod();
    secondMethod();
}

componentMethod() 首先运行。但是,总是得到数组的“未定义”

一种解决方案是在订阅数据时将 secondMethod() 放入 componentMethod() 中。但我不想这样做,因为我需要使用循环,这将花费太长时间。

标签: javascriptangulartypescriptobservablesubscribe

解决方案


我认为您应该澄清这部分问题:

“但我不想这样做,因为我需要使用循环,这将花费太长时间”

您需要使用什么循环?因为它的约束可能是问题的基础......

根据您的解释,我(至少)看到了这个解决方案:

componentMethod() {
  // get from the service
  return this.otherService.serviceMethod().pipe(
    map(data => {
      this.array = data;
    })
  );
}

mainMethodMethod(){
    componentMethod().subscribe(() => {
        secondMethod();
    })
}

推荐阅读