我已经在Django中构建了RestApi,并在localhost:8000/project/list
和project-details
的{{1}}接收了JSON响应
我还创建了用于接收JSON数据的相应服务,类和组件。我还能够获取localhost:8000/project/details/:id
和project_list
。
当我执行GET project_details
时,它会给出DATA的JSON响应,但也会在运行时给出此错误。
“ ProjectDetailsComponent.html:18错误TypeError:无法读取未定义的属性'id'。”
project.ts(类)
Project_detials
ProjectDetailsComponent.ts(组件)
export class Project_list {
id : number;
projectname : string;
}
export class Project_details {
id : number;
projectname : string;
project_status : string;
description : string;
start_date : Date;
due_date : Date;
}
```
# project.service.ts (Service)
```
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Project_list,Project_details } from '../models/project';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ProjectService {
private projectUrl: string;
constructor(private http: HttpClient) {
this.projectUrl = 'http://localhost:8000/project';
}
public findAllProjects(): Observable<Project_list[]>
{
return this.http.get<Project_list[]>(this.projectUrl+'/list');
}
public findProjectById(id:number) : Observable<any>
{
return this.http.get<Project_details>(this.projectUrl+'/details/'+id+'/');
}
}
```
# ProjectListComponent.ts (Component)
```
import { Component, OnInit } from '@angular/core';
import { ProjectService } from '../../../services/project.service'
import { Project_list } from '../../../models/project'
@Component({
selector: 'app-project-list',
templateUrl: './project-list.component.html',
styleUrls: ['./project-list.component.css']
})
export class ProjectListComponent implements OnInit {
project_list : Project_list[];
constructor( private projectService:ProjectService ) { }
ngOnInit() {
this.projectService.findAllProjects().subscribe(data => {
this.project_list = data;
console.log(data);
});
}
}
ProjectDetailsComponent.html(HTML)
import { Component, OnInit } from '@angular/core';
import { ProjectService } from '../../../services/project.service';
import {Project_details} from '../../../models/project';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-project-details',
templateUrl: './project-details.component.html',
styleUrls: ['./project-details.component.css']
})
export class ProjectDetailsComponent implements OnInit {
project_details : Project_details;
id:number;
private sub:any;
constructor(private projectService:ProjectService, private route: ActivatedRoute) { }
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.id = +params['id'];
console.log(this.id);
});
this.projectService.findProjectById(this.id).subscribe(data => {
this.project_details = data;
console.log(this.project_details);
});
}
}
答案 0 :(得分:0)
还可以粘贴API响应中返回的JSON对象吗?
Django可能会发送数据数组。
请尝试(在ProjectDetailsComponent.ts(组件)中)
this.project_details = data[0];
装的
this.project_details = data;