Angular调用REST接口返回JSON对象,组件读取响应数据为undefined如何解决?
问题原因
- 异步执行顺序问题:
getLocalObjectsFromREST()返回的是RxJS的Observable对象,调用subscribe之后HTTP请求是异步执行的,回调函数只有在请求成功返回之后才会触发给_localObjects赋值。你在ngOnInit里调用完方法立刻打印变量,这时候请求还没返回,变量自然是undefined。 - 构造函数拼写错误:代码里构造函数写的是
contructor,正确拼写是constructor,拼写错误会导致Angular的依赖注入失效,_restApi会保持undefined,根本不会发起HTTP请求,也就永远不会给_localObjects赋值。
解决方法
首先修复构造函数拼写,再把所有需要用到接口返回值的逻辑都移到subscribe回调内,保证赋值完成后再执行相关操作,修改后的代码参考如下:
export class AppComponent implements OnInit { _restApi: RestApiService | undefined; _localObjects: LocalObjects | undefined; // 修复构造函数拼写 constructor(restApi: RestApiService) { this._restApi = restApi; } ngOnInit() { this.getLocalObjectsFromService(); } getLocalObjectsFromService() { return this._restApi?.getLocalObjectsFromREST().subscribe((data: LocalObjects) => { this._localObjects = data; // 所有用到_localObjects的逻辑都放到回调内执行 console.log("Main object has a name of: " + this._localObjects?.mainObject.objName) console.log("Data Returned is " + this._localObjects); // 其他处理返回数据的逻辑也写在这里 }) } }
如果偏好同步写法,也可以用RxJS的firstValueFrom配合async/await实现:
import { firstValueFrom } from 'rxjs'; export class AppComponent implements OnInit { _restApi: RestApiService | undefined; _localObjects: LocalObjects | undefined; constructor(restApi: RestApiService) { this._restApi = restApi; } async ngOnInit() { await this.getLocalObjectsFromService(); // await执行完成后变量已经完成赋值,可以直接使用 console.log("Main object has a name of: " + this._localObjects?.mainObject.objName) console.log("Data Returned is " + this._localObjects); } async getLocalObjectsFromService() { if (!this._restApi) return; const data = await firstValueFrom(this._restApi.getLocalObjectsFromREST()); this._localObjects = data; } }
内容的提问来源于stack exchange,提问作者Ken Tola
相关产品推荐
相关产品推荐

