You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular2:ngOnInit中调用后端API后全局变量未被赋值

异步请求导致变量未赋值?问题分析与修复方案

Hey, I see exactly what's happening here—this is a classic async/order of execution issue. Let's break it down:

What's Wrong with Your Code

The this.http.get() call is asynchronous. That means when you call this.add(this.myArray) right after subscribing to the HTTP request, the request hasn't finished yet! The subscribe callback (where you assign this.myArray = data) only runs after the server sends back the response. So at the point you call add(), myArray is still uninitialized (hence undefined).

Here's the order your code runs in:

  1. You subscribe to route query params
  2. You build your request path and fire off the HTTP GET
  3. Immediately call this.add(this.myArray) (request is still pending, myArray is undefined)
  4. Later, the HTTP request completes, and this.myArray = data finally runs

Fix 1: Call add() Inside the Subscribe Callback

The simplest fix is to move your this.add() call into the subscribe's next callback—this ensures it only runs after the data has been assigned to myArray:

myArray: MyObject[]; 
requestPath: string; 
one: string; 
two: string; 
three: string; 
four: string; 

ngOnInit() { 
  this.activatedRoute.queryParams.subscribe((params: Params) => { 
    this.one = params['one']; 
    this.two = params['two']; 
    this.three = params['three']; 
    this.four = params['four']; 
    this.requestPath = this.getRequestPath(this.one,this.two,this.three,this.four); 

    this.http.get(this.requestPath) 
      // Note: If you're using Angular 4.3+, HttpClient auto-parses JSON—you can remove this .map() line
      .map(res => res.json()) 
      .subscribe( 
        data => { 
          this.myArray = data; 
          this.add(this.myArray); // Now this runs AFTER data is assigned!
        }, 
        err => console.error(err), 
        () => console.log('inside comparator oninit')
      ); 
  }); 
}

Fix 2: Use RxJS Operators (Cleaner for Async Flows)

If you want a more elegant approach (and avoid nested subscriptions), use RxJS operators like switchMap to chain your async operations:

import { switchMap } from 'rxjs/operators';

// ... (your class properties)

ngOnInit() { 
  this.activatedRoute.queryParams.pipe(
    switchMap((params: Params) => { 
      this.one = params['one']; 
      this.two = params['two']; 
      this.three = params['three']; 
      this.four = params['four']; 
      this.requestPath = this.getRequestPath(this.one,this.two,this.three,this.four); 
      // Return the HTTP observable to chain it
      return this.http.get(this.requestPath); 
    })
  ).subscribe( 
    data => { 
      this.myArray = data; 
      this.add(this.myArray); 
    }, 
    err => console.error(err), 
    () => console.log('inside comparator oninit')
  ); 
}

Quick Side Note

If you're using Angular 4.3 or later, the HttpClient module automatically parses JSON responses, so you can delete the .map(res => res.json()) line entirely—data will already be your parsed JSON object/array.

Also, your add function's parameter is named event, but you're passing myArray—renaming it to add(myArray: MyObject[]) will make your code more readable and avoid confusion.

内容的提问来源于stack exchange,提问作者roger_that

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:52:27