python - JSON 数据不是来自 Django REST API

标签 python json django angular

我有一个带有 Angular 前端的 Django REST API。我在前端没有收到任何错误,但没有 json 数据记录到控制台。

我有这样的服务:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';


@Injectable()
export class WeatherstatsService {

  constructor(private http:Http) {
    console.log("Hello World");

    this.getWeatherData();
    // this.getWeatherDataRecords();
  }

  weatherdata: any = {};

  private _WeatherStatsUrl = 'http://127.0.0.1:8000/weatherstats/weatherdata';

  getWeatherData() {
    return this.http.get(this._WeatherStatsUrl)
      .map((res:Response) => res.json());
  }

  getWeatherDataRecords() {
    this.getWeatherData().subscribe(weatherdata => {
      console.log(weatherdata)
    })
  }
}

像这样提供一个组件:

import { Component, OnInit } from '@angular/core';
import { WeatherstatsService } from '../weatherstats.service';

@Component({
  selector: 'weather-stats',
  templateUrl: './weather-stats.component.html',
  styleUrls: ['./weather-stats.component.css']
})
export class WeatherStatsComponent implements OnInit {

  data: any;

  constructor(private weatherstatsservice: WeatherstatsService) { }

  ngOnInit() {

    console.log(this.weatherstatsservice.getWeatherData().subscribe(data => this.data = data));

  }

}

我是 Django 和 Angular 的新手,当我在浏览器中测试 API 时,我得到了我想要的数据。可能发生了什么,这意味着我看不到我的 json 数据? (向刚才试图在类似问题上提供帮助的人表示歉意 - 我的大脑被所有这些新东西炸开了!)

控制台:

Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}
    closed
    :
    false
    destination
    :
    SafeSubscriber {closed: false, _parent: null, _parents: null, _subscriptions: null, syncErrorValue: null, …}
    isStopped
    :
    false
    syncErrorThrowable
    :
    false
    syncErrorThrown
    :
    false
    syncErrorValue
    :
    null
    _parent
    :
    null
    _parents
    :
    null
    _subscriptions
    :
    Array(1)
    0
    :
    MapSubscriber {closed: true, _parent: null, _parents: null, _subscriptions: null, syncErrorValue: null, …}
    length
    :
    1
    __proto__
    :
    Array(0)
    __proto__
    :
    Subscription

最佳答案

您现在正在控制台记录订阅,因此您在控制台中获得的输出是正确的。要控制台记录响应,请执行以下操作:

this.weatherstatsservice.getWeatherData()
  .subscribe(data => {
    this.data = data;
    console.log(this.data)
  })

关于python - JSON 数据不是来自 Django REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47580110/

相关文章:

python - python 中的自定义类 : does a method HAVE to be called with an instance?

python - Django 表格 : disable field if booleanfield is checked

jquery - 在 jQuery/javascript 中从 SQLite 数据构建 JSON

Django:从特定 id 作为起点获取 10 条数据的限制

python - 确定自进程最后一次输出以来的时间 - 使用 subprocess.Popen

python - JavaScript 的 String.fromCharCode 有 Python 版本吗?

django - 附加斜线不起作用

python - list_display 不起作用

java - 在保持LogicalTypes的同时将Parquet/Avro GenericRecord写入JSON

javascript - 按 Asc 顺序字符串化 JS 对象