【问题标题】:Why isn't my function returning the proper JSON data and how can I access it?为什么我的函数没有返回正确的 JSON 数据,我该如何访问它?
【发布时间】:2018-06-18 02:24:06
【问题描述】:

我正在运行服务以从 API 检索数据。这是其中一项服务:

robotSummary(core_id, channel_name){
const params = new HttpParams()


var new_headers = {
  'access-token': ' '
};
this.access_token = sessionStorage.getItem('access-token');
new_headers['access-token'] = this.access_token;

const myObject: any = {core_id : core_id, channel_name: channel_name};
const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;

const options = { params: new HttpParams(httpParams), headers: new_headers };
return this.http.get(this.baseURL + 'web_app/robot_summary/',options)
.subscribe(
res => console.log(res),
        )
   }
}

数据在控制台上正确显示,但我仍然无法访问各个键:

我是这样称呼它的:

ngOnInit(): void{

  this.login.getData(this.username, this.password).subscribe((data) => {
this.robotSummaryData = this.getRobotSummary.robotSummary(this.core_id, this.channel_name);
    console.log("robosummary"+ this.robotSummaryData)
  });
  }

当我调用此函数并将其分配给变量时,它在控制台上显示为 [object Object]。当我尝试使用 JSON.parse 时,它​​会抛出错误:类型订阅不可分配给参数字符串。如何访问数据?我想获取 JSON 对象并将其保存为具有适当属性的对象。谢谢!

【问题讨论】:

  • 将什么具体分配给变量?这只是正常的异步问题吗?
  • 我想将例如“状态”键作为属性分配给对象。我不明白你所说的正常异步问题是什么意思?

标签: json angular httpclient


【解决方案1】:

不要在你的服务内部订阅,在你的组件中订阅,如下改变你的服务,

robotSummary(core_id, channel_name){
    const params = new HttpParams()
    var new_headers = {
        'access-token': ' '
    };
    this.access_token = sessionStorage.getItem('access-token');
    new_headers['access-token'] = this.access_token; const myObject: any = { core_id: core_id, channel_name: channel_name };
    const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;

    const options = { params: new HttpParams(httpParams), headers: new_headers };
    return this.http.get(this.baseURL + 'web_app/robot_summary/', options)
        .map((response: Response) => response);
}

然后在你的组件中,

ngOnInit(){
        this.api..getRobotSummary.robotSummary(this.core_id, this.channel_name).subscribe((data) => {
        this.data = data;
        console.log(this.data); 
});
}

【讨论】:

  • 我得到错误:属性 'map' 在类型 'Observable' 上不存在
  • 你需要导入 import 'rxjs/add/operator/map'
  • 试过了,仍然显示同样的错误。我还需要登录调用在任何其他调用开始之前完成执行
  • 什么是角度版本
  • 角度版本 6.0.7
猜你喜欢
  • 2015-03-21
  • 2012-09-07
  • 2016-11-11
  • 2017-12-05
  • 2015-05-09
  • 1970-01-01
  • 1970-01-01
  • 2017-09-13
相关资源
最近更新 更多