我是Angular的新手,我正在创建一个测试应用程序,以加快我对该主题的理解。最近,我遇到了将Angular2(FrontEnd)与Django(Backend)集成的挑战,方法是使用REST API获取数据。
文件:library.service.ts
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
// Project Modules
import { Library } from '../models';
@Injectable()
export class LibraryService {
private librariesUrl = 'http://127.0.0.1:8000/api/library/create-library/';
constructor(private http: Http) { }
private headers = new Headers({'Content-Type': 'application/json'});
private extractData(res: Response) {
return res.json();
}
private handleError (error: any) {
return Observable.throw(error.message || 'Server error');
}
getAll(): Observable<Library[]> {
return this.http.get(this.librariesUrl, {headers: this.headers})
.map((res) => this.extractData(res.json())).catch((err) => this.handleError(err));
}
}
文件:libraries.component.ts
import { Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
// Project Modules
import { Library } from '../models';
import { LibraryService } from './library.service';
@Component({
selector: 'app-libraries',
templateUrl: './libraries.component.html',
styleUrls: ['./libraries.component.css'],
})
export class LibrariesComponent implements OnInit {
libraries: Library[];
personalLibraries: Library[];
collaborativeLibraries: Library[];
constructor(private libraryService: LibraryService, private http: HttpClient) { }
ngOnInit(): void {
/*this.http.get('http://127.0.0.1:8000/api/library/create-library/').subscribe((data: Library[]) => {
console.log(data);
this.personalLibraries = data;
});*/
this.libraryService.getAll().subscribe(response => this.personalLibraries = response);
}
}
REST API
# Django Modules
from django.shortcuts import get_object_or_404
# REST Modules
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.decorators import api_view, authentication_classes, permission_classes
# Project Modules
from .models import Resource, ResourceUserAssociation, Collection, Library
from mysite.utils import get_value_or_404, get_value_or_default, get_boolean
from .serializers import LibrarySerializer, CollectionSerializer
# TODO: Check user authentication here
class CreatorLibraryAPI(APIView):
def get(self, request, format=None):
# slug = get_value_or_404(request.GET, 'slug')
lib_object = Library.objects.filter(type='personal')
sdata = LibrarySerializer(lib_object, many=True).data
return Response(sdata, status=status.HTTP_200_OK)
JSON我期待
[
{
"slug": "tech-stack",
"title": "Technology Stack",
"description": "Library of resources related to Technology",
"type": "personal"
},
{
"slug": "biz-stack",
"title": "Technology Stack",
"description": "Library of resources related to Business",
"type": "personal"
},
{
"slug": "design-stack",
"title": "Design Stack",
"description": "Library of resources related to Design",
"type": "personal"
}
]
重要 当我尝试仅在Component中获取数据时,我成功地获得了结果[请参阅libraries.components.ts中的注释代码]。但不知怎的,它在服务中没有用,我是否在使用Observables做错了什么?
注意 此问题与Question here非常相似。
非常感谢社区提前:)
答案 0 :(得分:0)
我做了很少的改变: 使用HttpClient而不是Http。这允许我删除.map(),因为HttpClien已经返回JSON(而不是整个响应)。
正确文件:library.service.ts
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Headers } from '@angular/http';
import {HttpClient} from '@angular/common/http';
// Project Modules
import { Library } from '../models';
@Injectable()
export class LibraryService {
private librariesUrl = 'http://127.0.0.1:8000/api/library/create-library/';
constructor(private http: HttpClient) { }
private headers = new Headers({'Content-Type': 'application/json'});
private handleError (error: any) {
console.log('---------- CATCH ERROR ----------');
return Observable.throw(error.message || 'this is some random server error');
}
getAll(): Observable<Library[]> {
return this.http.get(this.librariesUrl).catch((err) => this.handleError(err));
}
}