【问题标题】:Angular - parse json string created by json dumpsAngular - 解析由 json 转储创建的 json 字符串
【发布时间】:2018-05-28 12:59:32
【问题描述】:

我找不到有用的解决方案。

我在 python 3.6 (django rest-framwork) 服务器端和 angular 5 客户端工作。

在服务器上:

class TypesView(APIView):
    def get(self,request):
        a = ['Cat','Dog']
        j = json.dumps(a)
        return Response(data=j, status=status.HTTP_200_OK)

我试图在客户端解析这个:

  public getAnimalRaces(): Observable<string[]>{
     const path = environment.apiEndpoint + "animals/races/"
    return this._http_client.get<string[]>(path)
  }

但我不断收到: 尝试区分 '["Cat", "Dog"]' 时出错。只允许使用数组和可迭代对象

这是返回给客户的:

"[\"Cat\", \"Dog\"]"

有什么想法吗?

【问题讨论】:

    标签: javascript json angular python-3.x typescript


    【解决方案1】:

    你正在尝试迭代一个字符串。

    您需要将响应解析为 JSON,这会将响应转换为一个数组,然后您可以在模板中将其与 *ngFor 一起使用。

    this._http_client.get<string[]>(path)
      .map((res) => JSON.parse(res));
    

    【讨论】:

    • 唯一不同的是:this._http_client.get 而不是 string[]。谢谢!
    【解决方案2】:

    您的回复是字符串化的。为了使其工作,您必须在服务器端将其作为纯 JSON 发送,或将其视为字符串并在客户端使用 JSON.parse()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多