【问题标题】:Why does this variable always return null ? Angular Service为什么这个变量总是返回 null ?角服务
【发布时间】:2020-01-20 01:15:40
【问题描述】:

现在 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 文件中使用它。

【问题讨论】:

标签: javascript angular httpclient angular-services


【解决方案1】:

由于异步调用,console.log(this.res) 在处理服务器调用之前执行。

改变

this.getdata().subscribe(data=>
{
  this.res=data
});
console.log(this.res)

收件人

this.getdata().subscribe(data=>
  {
   this.res=data; 
   console.log(this.res)
  });

【讨论】:

  • 好的,这将控制数据,我想将数据移出范围
  • @Aboulezz:您可以调用任何函数并将数据传递给它,以使其“超出范围”。您不能做的是在实际收到数据之前访问数据,就像您在代码 atm 中所做的那样。
  • 数据在this.res 的范围外解析,但您需要等到服务器调用处理完毕,否则this.res 将为空
猜你喜欢
  • 2019-09-11
  • 2020-06-17
  • 2014-07-09
  • 2022-01-14
  • 2014-09-12
  • 2019-09-18
  • 2014-09-02
  • 2015-02-27
  • 2021-01-10
相关资源
最近更新 更多