为我服务:
public sendUpdate(idBombeamento:number): Observable<any>{
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('access_token')}`
});
//console.log(headers.get('Authorization'));
const requestOptions = { headers: headers };
return this.http.get<any>(`${this.url}/${idBombeamento}`,requestOptions);
}
在我的组件中:
import { catchError, interval, map, Observable, switchMap, throwError } from 'rxjs';
export class BombeamentoComponent implements OnInit{
protected idBombeamento:number=0;
constructor(
private bombService:BombeamentoService,
private routeA: ActivatedRoute,
private _snackBar: MatSnackBar,
private http:HttpClient){
this.routeA.params.subscribe(params => {
this.idBombeamento = params['id'];
});
}
如何每 10 秒发出一次 GET 请求来更新组件的数据?
依赖关系:
"dependencies": {
"@angular/animations": "^16.1.0",
"@angular/cdk": "^16.2.0",
"@angular/common": "^16.1.0",
"@angular/compiler": "^16.1.0",
"@angular/core": "^16.1.0",
"@angular/forms": "^16.1.0",
"@angular/material": "^16.2.0",
"@angular/platform-browser": "^16.1.0",
"@angular/platform-browser-dynamic": "^16.1.0",
"@angular/router": "^16.1.0",
"@auth0/angular-jwt": "^5.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.13.0"
},
我用多种方式测试了它,但是GET命令并不是每10秒发送到后端一次,它总是从第一个请求中获取响应:
ngOnInit():void{
setInterval(() => {
this.bombService.sendUpdate(this.idBombeamento).subscribe({
next: (res)=>{
this.retornoChamado = res;
this.openSnackBar1("Enviado com sucesso!","",false);
console.log(this.retornoChamado);
},
error:(e)=>console.log(e),
});
}, 10000);
}
ngOnInit():void{
interval(10000).subscribe(res=>{this.bombService.sendUpdate(this.idBombeamento).subscribe((res2)=>{
console.log("passou");
console.log(res2);
})});
}
你可以这样尝试吗
import { interval } from 'rxjs';
import { switchMap } from 'rxjs/operators';
// ...
ngOnInit(): void {
interval(10000)
.pipe(
switchMap(() => this.bombService.sendUpdate(this.idBombeamento))
)
.subscribe(
(res) => {
console.log("Received response:", res);
},
(error) => {
console.error("Error:", error);
}
);
}