简体   繁体   English

参数未定义的Angular 2路由

[英]Angular 2 Routing with parameter undefined

I'm trying to create a route in Angular 2 that takes me to data of a json file, depending on the id. 我正在尝试在Angular 2中创建一条路由,该路由根据ID将我带到json文件的数据。 For instance I have 10001.json, 10002.json, 10003.json, etc... 例如我有10001.json,10002.json,10003.json等...

People should be able to get to their patientfile by typing in that particular id as an url, but so far that's not working. 人们应该可以通过输入特定的id作为url来访问他们的Patientfile,但到目前为止这是行不通的。 I'm actually getting : 我实际上得到:

GET http://localhost:4200/assets/backend/patienten/undefined.json 404 (Not Found) GET http:// localhost:4200 / assets / backend / patienten / undefined.json 404(未找到)

This is my 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);


  }
}

This is the routing, very basic: 这是路由,非常基本:

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}

];

And the service: 和服务:

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)
  }
}

The problem is that you call getData before this.id is populated. 问题是您在填充this.id之前先调用getData。 Just change places 换个地方

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

  }

Edited: route.params is an Observable, so you need to use it like: 编辑: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.
});

You need to provide those files as static assets to your angular app, otherwise the angular router will try route those requests to your in-app routes, which wont have a matching route. 您需要将这些文件作为静态资产提供给您的角度应用程序,否则角度路由器将尝试将这些请求路由到您的应用程序内路由,而该应用内路由将没有匹配的路由。

You can do this by editing the 'assets' value in your angular-cli.json , and specifying any files and folders you would like to have accessible via your routing. 您可以通过编辑angular-cli.json的'assets'值并指定您希望通过路由访问的任何文件和文件夹来实现。 (and also copied by the angular cli to your dist folder during build.) (并在构建过程中通过角度cli复制到dist文件夹。)

As an example, the following would copy and allow routing to the following: 例如,以下内容将复制并允许路由到以下内容:

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

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

For more in depth examples, have a look at the Angular CLI wiki here: https://github.com/angular/angular-cli/wiki/stories-asset-configuration 有关更多深入的示例,请在此处查看Angular CLI Wiki: https : //github.com/angular/angular-cli/wiki/stories-asset-configuration

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM