首页 > 解决方案 > 在 angular observable 内发出多个 http 请求

问题描述

我正在尝试使用 angular 中的 http 模块在我的应用程序组件的 init 上的 service.ts 文件中发出请求....我的问题是我的函数 getStats() 是一个可观察的,它只是在制作之前返回统计信息对我的 json 服务器的第二个 post 请求

我想做的是确保两个请求在返回之前完成

我尝试在我的函数中使用 promise,但我的 IDE 抛出了一个错误,即它们不允许在 observables 中使用,我尝试使用回调并且我得到了类似的错误。我试图了解在此函数中处理多个请求的有效语法是什么,因为请求是在“同一”时间向 2 个不同的位置发出的

非常感谢我对noobish要求的任何见解:)

规格.service.ts

export class SpecsService {
  private apiUrl = 'http://localhost:3000'
  constructor(private http:HttpClient) {}

  getStats():Observable<Object>{

    //get current stats
    let stats = this.http.get(`http://localhost:8888/fetchStats`)
  
    //send stats to json server store
    const url = `${this.apiUrl}/progressionData`; //json server collection location
    this.http.post(url,stats,httpOptions)

    return stats
 }

}

我的 app.component.ts

import { Component, Output,EventEmitter } from '@angular/core';
import { SpecsService } from 'src/app/specs.service';
import {Observable} from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'pctothemoon';
  stats: any

  
  constructor(private specsService: SpecsService) {
    this.stats = this.specsService.getStats();
   }

  ngOnInit(): void {
    //current stats
    this.specsService.getStats().subscribe((response) => this.stats=response)
    }
}

标签: angulartypescripthttpasynchronous

解决方案


推荐阅读