【问题标题】:Angular HTTP Get response is string not objectAngular HTTP Get 响应是字符串而不是对象
【发布时间】:2022-03-27 17:35:36
【问题描述】:

我正在尝试对我的本地服务器进行 http get 查询,然后从返回的对象中解析结果以显示给用户。无论我尝试什么,来自请求的数据和我尝试分配的 serverData 对象都保留为字符串。请帮帮我,我快疯了!

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  showsFound: boolean = false;
  unknownShow: boolean = false;

  url: string;
  host: string;
  show: string;
  serverData: object;
  httpOptions: object = {
    responseType: 'json'
  }

  constructor(private httpClient: HttpClient){
  }

  public getRecommendations(url) {
    var subString = url.split( '/' );
    this.host = subString[4];
    this.show = subString[6];
    this.httpClient.get('http://127.0.0.1:5002/api/v1/recommender/'+this.host+'/'+this.show, this.httpOptions)
    .subscribe(data => {
      console.log(typeof data);            // logs 'string'
      this.serverData = <object>data;
      console.log(typeof this.serverData); // logs 'string'
    })
  }

}

运行 console.log(data) 给出以下输出

{"name":"Url","data":["https:\/\/www.website.com\/shows\/show_name_1\/","https:\/\/www.website.com\/shows\/show_name_2\/"]}

我尝试设置为一个对象并传递给 this.serverData 但它仍然是一个字符串

编辑

评论表明它与网络响应有关,因此附上了查询和响应标头的照片

【问题讨论】:

标签: angular typescript http


【解决方案1】:

而不是 this.serverData = data;

试试 this.serverData = JSON.parse(data);

【讨论】:

    【解决方案2】:

    替换这部分代码

     public getRecommendations(url) {
        var subString = url.split( '/' );
        this.host = subString[4];
        this.show = subString[6];
        this.httpClient.get('http://127.0.0.1:5002/api/v1/recommender/'+this.host+'/'+this.show, this.httpOptions)
        .subscribe(data => {
          console.log(typeof data);            // logs 'string'
          this.serverData = JSON.parse(data);
          console.log(typeof this.serverData); // logs 'string'
        })
      }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 2018-08-02
      • 1970-01-01
      • 2017-08-09
      • 2023-01-31
      • 2011-08-06
      相关资源
      最近更新 更多