我正在尝试在 Angular 2 中创建一个路由,该路由将我带到 json 文件的数据,具体取决于 id。例如我有 10001.json、10002.json、10003.json 等...
人们应该能够通过输入特定的 id 作为 url 来访问他们的患者文件,但到目前为止这还行不通。我实际上得到:
GET http://localhost:4200/assets/backend/patienten/undefined.json 404(未找到)
这是我的耐心组件:
import { Component, OnInit } from '@angular/core';
import {PatientService} from "../patient.service";
import {Patient} from "../models";
import {ActivatedRoute, Params} from "@angular/router";
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'app-patient',
templateUrl: './patient.component.html',
styleUrls: ['./patient.component.sass']
})
export class PatientComponent implements OnInit {
patient:Patient[];
id:any;
errorMessage:string;
constructor(private patientService:PatientService, private route: ActivatedRoute) { }
ngOnInit():void {
this.getData();
this.id = this.route.params['id'];
this.patientService.getPatient(this.id)
.subscribe(patient => this.patient = patient);
}
getData() {
this.patientService.getPatient(this.id)
.subscribe(
data => {
this.patient = data;
console.log(this.patient);
}, error => this.errorMessage = <any> error);
}
}
这是路由,非常基本:
import {Routes} from "@angular/router";
import {AfdelingComponent} from "./afdeling/afdeling.component";
import {PatientComponent} from "./patient/patient.component";
export const routes: Routes = [
{path: '', component: AfdelingComponent},
{path: 'patient/:id', component: PatientComponent}
];
和服务:
import { Injectable } from '@angular/core';
import {Http, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from "rxjs";
import {Patient} from "./models";
@Injectable()
export class PatientService {
private patientUrl = "/assets/backend/patienten/";
constructor(private http: Http) { }
getPatient(id:any): Observable<Patient[]>{
return this.http.get(this.patientUrl + id + '.json' )
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
addPatient(afdelingsNaam: string, afdeling: any): Observable<Patient> {
let body = JSON.stringify({"afdelingsNaam": afdelingsNaam, afdeling: afdeling});
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(this.patientUrl, body, options)
.map(res => <Patient> res.json())
.catch(this.handleError)
}
}