现在花了8个小时来解决一个琐碎的问题&我真不敢相信!
下面是一个角服务脚本
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class GetStockDataService {
constructor(public http:HttpClient) { }
RequestData={"query":"{\n stock{\n history{\n \n low\n high\n demand\n }\n }\n}"}
getstockdata(){
return this.http.post('http://localhost:3000/',this.RequestData)
}
}下面是一个组件脚本,它调用该服务
import { Component, OnInit } from '@angular/core';
import { GetStockDataService } from '../services/get-stock-data.service';
import { Platform } from '@ionic/angular';
@Component({
selector: 'app-Stocks',
templateUrl: 'Stocks.page.html',
styleUrls: ['Stocks.page.scss']
})
export class StocksPage implements OnInit {
constructor(private GetStockData:GetStockDataService , private platform : Platform) {}
res:any
ngOnInit(){
this.getdata().subscribe(data=>{this.res=data});
console.log(this.res)
}
getdata(){
return this.GetStockData.getstockdata() }} 为什么"res“变量总是返回NULL?知道当我把控制台日志中的变量放在订阅部分中的函数中。它返回数据,但我不能使这个变量是全局的.我怎么能这么做?我只想从订阅获取数据到"res“变量,以便稍后使用HTML文件。
发布于 2020-01-20 01:25:56
由于异步调用,console.log(this.res)在处理服务器调用之前执行。
Change
this.getdata().subscribe(data=>
{
this.res=data
});
console.log(this.res)到
this.getdata().subscribe(data=>
{
this.res=data;
console.log(this.res)
});https://stackoverflow.com/questions/59815902
复制相似问题