如何在Angular 5 +中异步等待?

问题描述 投票:0回答:4

打字稿:

getSocialDataTwitter(searchQuery) {
  this.fetchLists(searchQuery);
  const headers = new HttpHeaders().set('content-type', 'application/json');
  return this.http.post<RightOperatorPaneltwitter>(this.baseUrl + 'api/OperationData/GetAllTweetsByNamePost', this.lists, { headers }).subscribe(result => {
    this.tweets = result;
  }, error => console.error(error));
}

fetchLists(searchQuery) {
  this.listService.getLists()
    .subscribe((data: List[]) => {
      data.forEach(d => {
        if (d.name === searchQuery) {

          this.lists = d;
        }
      })
    });
}

我是Angular 5 + .Netcore 2.0的新手。我想使用fetchLists使用node.js从我的mongo db获取数据。并将其发送给我的api控制器。我成功地从数据库中获取数据。第一次单击后,对象到我的控制器处于默认初始化状态,在第二次单击后,控制器获取我期望的数据。有没有办法等待fetchLists完成进程然后执行请求到api控制器的帖子。我希望用户在点击一次后看到数据。

我错误地认为使用.subcribe是异步的吗?

angular typescript asp.net-core-2.0
4个回答
1
投票

我想你想要的是使用合并映射链接你的两个调用。我修改了你的例子以显示要做什么。

首先,你的fetchLists方法不应该订阅列表服务,而只是转换数据并返回结果observable。然后在你的getSocialDataTwitter方法中,你将调用fetchLists并使用mergeMap链接你的第二个http调用。

fetchLists(searchQuery) {
    // Make note how we map the result and then return the observable 
    // without subscribing.
    return this.listService.getLists()
    .pipe(
        map((data: List[]) => data.find(d => d.name === searchQuery))
    )
}

getSocialDataTwitter(searchQuery) {
    // As the headers and url will not change, we can define them here
    const headers = new HttpHeaders().set('content-type', 'application/json');
    const url = this.baseUrl + 'api/OperationData/GetAllTweetsByNamePost';

    // Here we call our initial method, but instead of subscribing directly
    // we use mergeMap to chain our observables
    this.fetchLists(searchQuery)
        .pipe(
            // Lists is the result we created with the map in fetchLists.
            mergeMap(lists => this.http.post<RightOperatorPaneltwitter>(url, lists, { headers }))
        )
        // Only after we subscribe here, the list service is called.
        .subscribe(result => this.tweets = result);
}

1
投票

如果我理解正确,您可以在此处执行发布请求:

fetchLists(searchQuery) {
  this.listService.getLists()
    .subscribe((data: List[]) => {
      data.forEach(d => {
        if (d.name === searchQuery) {

          this.lists = d;
        }
      })

      // EXECUTE HERE
    });
}

这样,您就可以获取列表,处理它然后执行您的帖子。使用observables称为反应式编程。如上所述here

反应式编程是使用异步数据流进行编程


1
投票

据我所知,你的问题是你的问题是this.fetchLists(searchQuery)被执行但是在订阅方法填充列表之前,API-Post已经完成。

我认为你可以使用ES2017 async / await功能解决这个问题:

async getSocialDataTwitter(searchQuery) {
  await this.fetchLists(searchQuery);
  const headers = new HttpHeaders().set('content-type', 'application/json');
  return this.http.post<RightOperatorPaneltwitter>(this.baseUrl + 'api/OperationData/GetAllTweetsByNamePost', this.lists, { headers }).subscribe(result => 
  {
   this.tweets = result;
  }, error => console.error(error));
}

0
投票

您可以创建另外的方法来调用fetchlist并返回可观察的结果,然后我们可以调用getSocialDataTwitter()方法。

fetchLists(searchQuery) {
  return this.listService.getLists()
    .subscribe((data: List[]) => {
      data.forEach(d => {
        if (d.name === searchQuery) {
          this.lists = d;
        }
      });
      return Observable.of(this.lists);
    });
}

getData(){
    return this.fetchLists(searchQuery).pipe(
       this.fetchLists(),
       switchMap((result)=>{
          return this.getSocialDataTwitter();
       })
    )
}
© www.soinside.com 2019 - 2024. All rights reserved.