angular - 在 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)
}
}
解决方案
推荐阅读
- c# - 如果服务总线计数变为零,则发送邮件
- c++ - 从 shared_ptr 派生
- excel - Excel 中的唯一排名
- python - 如何获取 matplotlib 中所有标记的列表?
- python - 使用机械汤输入后显示为输入选项 - Python
- azure-active-directory - 将所有者添加到 Graph 中的组时未收到电子邮件
- django - 修复错误:django.db.utils.OperationalError: no such table: auth_group
- docker - 无法在 Mac OS 主机上的两个 Docker 容器之间发送/接收 UDP 通信
- c# - 为什么 C# 表单应用程序中的 Firebase 不是实时的?
- java - 实现与firebase一起使用的倒数计时器