【问题标题】:Angular 2 Error while fetching data from Django Rest API从 Django Rest API 获取数据时出现 Angular 2 错误
【发布时间】:2017-07-30 09:52:55
【问题描述】:

我是 Angular 的新手,我正在创建一个测试应用程序来加快我对该主题的理解。最近我遇到了一个挑战,即通过使用 REST API 获取数据来集成 Angular2(FrontEnd) 和 Django(Backend)。

文件: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"
    }
]

重要 当我尝试仅在组件中获取数据时,我成功地获得了结果 [参见 library.components.ts 中的注释代码]。但不知何故,它在服务中不起作用,我对 Observables 做错了吗?

注意 这个问题和Question here很相似。

提前感谢社区:)

【问题讨论】:

  • 你遇到了什么错误?
  • 你没有在服务 ts 文件中导入Response;你在extractData函数中使用的那个
  • 谢谢。胸围仍然得到同样的错误
  • 发布您遇到的错误

标签: django angular django-rest-framework angular-services


【解决方案1】:

我做了一些改变: 使用 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));
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2017-01-04
    相关资源
    最近更新 更多