我正在使用Django 2.1.5和Angular 7.3.1。我有一个Django后端类DetailView,我正尝试使用该类将对象传递给Angular前端。我知道DetailView运行良好,因为使用Django渲染模板时可以看到该对象。由于某种原因,我似乎无法通过Django API将其传递给Angular。
当我加载页面时,dogdetail
上没有任何显示,并且控制台显示错误:DogdetailComponent.html:2 ERROR TypeError: Cannot read property 'name' of undefined
at Object.eval [as updateRenderer]
我已经尝试了几种变体和语法等。我认为,如果Django API正确获取了对象,那么Angular应该可以从API端点提取它。
我使用Postman访问API端点http://127.0.0.1:8000/1/dogdetail/
,获得了dog对象,并且可以访问其属性。
我的django urls.py:
from django.urls import path
from .views import DogList, DogDetailDjango, index
urlpatterns = [
path('', index, name='index'),
path('dogs/', DogList.as_view(), name='doglist'),
path('<int:pk>/dogdetail/', DogDetailDjango.as_view(), name='dogdetail'),
]
dogdetail.component.ts:
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service'
import { Dog } from '../dog'
@Component({
selector: 'app-dogdetail',
templateUrl: './dogdetail.component.html',
styleUrls: ['./dogdetail.component.scss']
})
export class DogdetailComponent implements OnInit {
dogdetail : Dog[];
constructor(private apiservice: ApiService) { }
ngOnInit() {
this.getDog();
}
getDog(): void {
this.apiservice.getDogDetail().subscribe(dogdetail=> this.dogdetail = dogdetail)
console.log(this.dogdetail);
}
}
api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http"
import { DogListComponent } from './dog-list/dog-list.component';
import { Dog } from './dog'
import { Observable, of } from 'rxjs'
@Injectable({
providedIn: 'root'
})
export class ApiService {
apiURL: string = 'http://127.0.0.1:8000'
constructor(private httpClient: HttpClient) { }
public getDogDetail(): Observable<Dog[]> {
return this.httpClient.get<Dog[]>(`${this.apiURL}/1/dogdetail`);
}
}
dogdetail视图Django:
class DogDetailDjango(DetailView):
model = Dog
serializer_class = DogSerializer
template_name = 'detail.html'
dogdetail.component.html
dogdetail works!
{{ dogdetail }}
<h1>{{ dogdetail.name }} </h1>
答案 0 :(得分:0)
@SimonK的答案正确,在安装适用于Google chrome的CORS插件后,我只能摆脱错误。我首先尝试创建正确的标题和所有内容,但只有在安装了插件之后,我才停止出现错误,因此无法正常工作。