Angular 2 参数未定义的路由
Angular 2 Routing with parameter undefined
我正在尝试在 Angular 2 中创建一个路由,根据 ID 将我带到 json 文件的数据。例如,我有 10001.json、10002.json、10003.json 等...
人们应该能够通过以 url 形式输入特定 ID 来访问他们的患者档案,但到目前为止这还行不通。我实际上得到了:
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)
}
}
您需要将这些文件作为静态资产提供给您的 angular 应用程序,否则 angular 路由器将尝试将这些请求路由到您的应用程序内路由,而这些路由不会有匹配的路由。
您可以通过编辑 angular-cli.json
中的 'assets' 值并指定您希望通过路由访问的任何文件和文件夹来实现。 (并在构建期间由 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
问题是您在填充 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.
});
我正在尝试在 Angular 2 中创建一个路由,根据 ID 将我带到 json 文件的数据。例如,我有 10001.json、10002.json、10003.json 等...
人们应该能够通过以 url 形式输入特定 ID 来访问他们的患者档案,但到目前为止这还行不通。我实际上得到了:
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)
}
}
您需要将这些文件作为静态资产提供给您的 angular 应用程序,否则 angular 路由器将尝试将这些请求路由到您的应用程序内路由,而这些路由不会有匹配的路由。
您可以通过编辑 angular-cli.json
中的 'assets' 值并指定您希望通过路由访问的任何文件和文件夹来实现。 (并在构建期间由 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
问题是您在填充 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.
});