0

我正在尝试在 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)
  }
}
4

2 回答 2

1

问题是您在this.id填充之前调用 getData 。只是换个地方

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

  }

编辑: route.params 是一个 Observable,所以你需要像这样使用它:

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.
});
于 2017-06-04T18:31:21.220 回答
0

您需要将这些文件作为静态资产提供给您的 Angular 应用程序,否则 Angular 路由器将尝试将这些请求路由到您的应用程序内路由,这些路由不会有匹配的路由。

您可以通过编辑 'assets' 值angular-cli.json并指定您希望通过路由访问的任何文件和文件夹来执行此操作。(并且在构建期间也由 angular cli 复制到您的 dist 文件夹中。)

例如,以下内容将复制并允许路由到以下内容:

  • src/assets/*(整个文件夹)
  • src/somefolder/*(整个文件夹)
  • src/favicon.ico
  • src/web.config

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

有关更深入的示例,请在此处查看 Angular CLI wiki:https ://github.com/angular/angular-cli/wiki/stories-asset-configuration

于 2017-06-04T18:02:25.493 回答