Angular中如何在GET请求中访问POST请求返回的ID变量
问题根因
你遇到的问题本质是异步请求的执行顺序问题:
- Angular HttpClient发出的HTTP请求是异步非阻塞的,调用
createItem()方法后,程序不会等待POST请求返回结果,就会直接执行后续的getItem() - 此时POST请求的回调还没触发,
id还是初始的空字符串,所以GET请求拼接的ID是空值 - HTML中可以正常显示
id是因为Angular的变更检测机制,id被赋值后会主动触发视图更新,因此可以正常渲染
解决方案
方案1:在POST请求回调中调用GET(最简修改)
修改createItem方法,在拿到id之后再执行getItem(),同时删除ngOnInit中的getItem()调用,修改后的代码如下:
import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { HttpHeaders } from '@angular/common/http'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', Authorization: '...', }), }; type CreatedItem = {id: string; inventory: []} @Component({ selector: 'home-component', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'], }) export class HomeComponent implements OnInit { url = 'url here'; id = ""; constructor(private httpClient: HttpClient) {} ngOnInit(): void { this.createItem(); } createItem() { this.httpClient.post<CreatedItem>(this.url, null, httpOptions).subscribe((res) => { this.id = res.id; // 拿到ID后再执行GET请求 this.getItem(); }); } getItem() { this.httpClient .get<any>( this.url + this.id, httpOptions ) .subscribe((res) => { console.log('GET请求返回结果:', res); }); } }
方案2:使用RxJS操作符链式调用(更符合Angular最佳实践)
通过switchMap操作符将两个请求串行,避免嵌套回调,代码更易维护:
import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { HttpHeaders } from '@angular/common/http'; import { switchMap } from 'rxjs/operators'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', Authorization: '...', }), }; type CreatedItem = {id: string; inventory: []} @Component({ selector: 'home-component', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'], }) export class HomeComponent implements OnInit { url = 'url here'; id = ""; constructor(private httpClient: HttpClient) {} ngOnInit(): void { this.createItem().pipe( switchMap((res) => { this.id = res.id; return this.getItem(); }) ).subscribe((getRes) => { console.log('GET请求返回结果:', getRes); }) } createItem() { // 直接返回Observable,不在方法内部subscribe return this.httpClient.post<CreatedItem>(this.url, null, httpOptions); } getItem() { return this.httpClient.get<any>( this.url + this.id, httpOptions ); } }
内容的提问来源于stack exchange,提问作者janesbeat
相关产品推荐
相关产品推荐

