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);
}
}
输出是这样的:
this is my prices class object undefined
api: this is what I get from the $, $ $
如您所见,第一条消息显示在第二条消息中,第二条消息位于第一位,但未定义,
显然发生的事情是代码不是在等待响应的到来,而是同步的,为什么?不是 observable.Subscribe(响应 ==> 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);
}
}
如果您有一个依赖于价格的函数,那么您可以在订阅中执行这些函数。
像这样:
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 ...}
}
我有以下代码:
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);
}
}
输出是这样的:
this is my prices class object undefined
api: this is what I get from the $, $ $
如您所见,第一条消息显示在第二条消息中,第二条消息位于第一位,但未定义, 显然发生的事情是代码不是在等待响应的到来,而是同步的,为什么?不是 observable.Subscribe(响应 ==> 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);
}
}
如果您有一个依赖于价格的函数,那么您可以在订阅中执行这些函数。 像这样:
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 ...}
}