2017-06-04 137 views
0

我正在嘗試在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) 
    } 
} 

回答

1

的問題是,你撥打的getData填充this.id之前。 只是換個地方

ngOnInit():void { 
    this.id = this.route.params['id']; 
    this.getData(); 
    this.patientService.getPatient(this.id) 
    .subscribe(patient => this.patient = patient); 

    } 

編輯: route.params是可觀察到的,所以你需要使用它喜歡:

this.sub = this.route.params.subscribe(params => { 
    this.id = +params['id']; // (+) converts string 'id' to a number 

    // In a real app: dispatch action to load the details here. 
}); 
+0

我試過了,但我得到了同樣的錯誤。我認爲我們在這裏是正確的道路,只是不知道如何解決它。 –

+0

請告訴我,爲什麼你需要運行'this.patientService.getPatient(this.id)'兩次?首先在'getData'中,然後明確 –

+1

是的,那是我的錯誤。我刪除了明確的一個......同樣的錯誤仍然存​​在。謝謝你幫助我:) –

0

您需要將這些文件作爲靜態資產提供給您的角度應用程序,否則角路由器會嘗試將這些請求路由到您的應用內路由,而這些路由不會有匹配的路線。

您可以通過編輯angular-cli.json中的'assets'值,並指定您希望通過路由訪問的任何文件和文件夾來完成此操作。 (並且還通過角CLI構建期間複製到DIST文件夾)。

作爲一個例子,下面將複製並允許路由到以下內容:

  • SRC /資產/ *(整個文件夾)
  • SRC/somefolder/*(整個文件夾)
  • SRC/favicon.ico的
  • SRC/web.config中

"assets": [ "assets", "somefolder", "favicon.ico", "web.config" ],

對於更深入的例子,看看在角CLI維基這裏:https://github.com/angular/angular-cli/wiki/stories-asset-configuration

+0

感謝您的幫助,但是這不是問題,因爲我有一個其他json文件放在同一個文件夾中,我可以識別。 –