我正在嘗試在Angular 2中創建一個路由,該路由將我帶到一個json文件的數據,具體取決於id。例如,我有10001.json,10002.json,10003.json等...Angular 2路由參數未定義
人們應該能夠通過輸入特定的id作爲url來獲取他們的患者文件,但到目前爲止這是行不通的。我真的開始:
GET http://localhost:4200/assets/backend/patienten/undefined.json 404(未找到)
這是我patientcomponent:
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)
}
}
我試過了,但我得到了同樣的錯誤。我認爲我們在這裏是正確的道路,只是不知道如何解決它。 –
請告訴我,爲什麼你需要運行'this.patientService.getPatient(this.id)'兩次?首先在'getData'中,然後明確 –
是的,那是我的錯誤。我刪除了明確的一個......同樣的錯誤仍然存在。謝謝你幫助我:) –