簡體   English   中英

Angular 調用 REST API 不等待數據到達

[英]Angular call to REST API not waiting for the data to arrived

我有以下代碼:

export class Whatever implements OnInitn{

    prices;

     ngOnInit(){
       this.CoinPricesService.getPrices().subscribe(
           pricesFromResponse => {
             this.prices = pricesFromResponse;
              console.log('this is what I get from the api: ', this.prices);
           }
       );
       
      console.log('this is my prices class object', this.prices);
     }
}

output 是這樣的:

這是我的價格 class object 未定義

api:這是我從$中得到的,$$

如您所見,第一條消息顯示在第二條消息中,第二條消息顯示在第一位,帶有 UNDEFINED,顯然發生的事情是代碼沒有等待響應的到來,正在同步,為什么? 不可觀察。訂閱(響應 ==> this.myVar = 響應); 打算照顧那個? 我不能在我的 class 的其他地方使用數據,因為當代碼到達那里時它總是未定義,請幫助

我的服務看起來像這樣:

@Injectable({
  providedIn: 'root'
})
export class CoinPricesService {

  private apiURl = 'https://api.forprices/blablabla';

  constructor(private http: HttpClient) { }

  getPrices(){
    return this.http.get<any>(this.apiURl);
  }
}

如果您有一個取決於價格的 function,那么您可以在訂閱中執行功能。 像這樣的東西:

    export class Whatever implements OnInitn{
    
        prices;
    
         ngOnInit(){
           this.CoinPricesService.getPrices().subscribe(
               pricesFromResponse => {
                 this.prices = pricesFromResponse;
                  console.log('this is what I get from the api: ', this.prices);
                  someFunction(pricesFromResponse)
               }
           );
           
          
         }
         someFunction(prices){//use price ...} 
    } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM