I've built a Django REST API using the Django Restapiframework, and it uses a serializer to return a json response:
from rest_framework import serializers
from .models import WeatherStatistics
class WeatherStatisticsSerializer(serializers.ModelSerializer):
class Meta:
model = WeatherStatistics
fields = '__all__'
In my Angular 4 front-end project I have a service:
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)
})
}
}
And I also have a component that uses that service:
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() {
this.data = this.weatherstatsservice.getWeatherData();
}
}
At the moment all I want it to do is log the json data from my api to the console oninit. So far tho, it does nothing. How do I get the json from Django into Angular?