我有以下代碼:
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);
}
}
輸出是這樣的:
這是我的價格類物件未定義
api:這是我從$中得到的,$$
如您所見,第一條訊息顯示在第二條訊息中,第二條訊息排在第一位,帶有未定義,顯然發生的事情是代碼沒有等待回應的到來,是同步的,為什么?不可觀察。訂閱(回應 ==> this.myVar = 回應);打算照顧那個?我不能在我班的其他地方使用資料,因為當代碼到達那里時它總是未定義,請幫助
我的服務看起來像這樣:
@Injectable({
providedIn: 'root'
})
export class CoinPricesService {
private apiURl = 'https://api.forprices/blablabla';
constructor(private http: HttpClient) { }
getPrices(){
return this.http.get<any>(this.apiURl);
}
}
uj5u.com熱心網友回復:
如果您有一個依賴于價格的函式,那么您可以在訂閱中執行這些函式。像這樣的東西:
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 ...}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/409347.html
標籤:
