Angular 2 个路由参数值未定义
Angular 2 route params value passed as undefined
基本上我试图从 url 段获取路由参数并将该参数传递给 API 调用。我可以在我的调试器中看到正在传递的值,但就在那时它传递给服务时它变得未定义。
我已经在这里待了几个小时了。我已经尝试了我能找到的每一个例子,但我仍然无法让它发挥作用。我真的可以为此使用一双新的眼睛。
出于本练习的目的,我导航到 /products/4
并且 API 端点应该是 /api/productsapi/4
以下是相关位:
app.routing.ts
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PostsComponent } from '../app/Components/posts.component';
import { HomeComponent } from '../app/Components/home.component';
import { ProductsComponent } from '../app/Components/products.component';
const appRoutes: Routes = [
{
path: 'home',
component: HomeComponent
},
{
path: 'posts',
component: PostsComponent
},
{
path: 'products',
children: [
{
path: '',
component: ProductsComponent
},
{
path: ':sectionID', //my first attempt at parameter routing... not very successful
component: ProductsComponent
},
{
path: '**',
redirectTo: 'products',
pathMatch: 'full'
}
]
},
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
}
];
export const
routing: ModuleWithProviders =
RouterModule.forRoot(appRoutes);
products.service.ts
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
@Injectable()
export class ProductsService {
constructor(private _http: Http) { }
get(url: string): Observable<any> { //url always ends up as api/productsapi/undefined
return this._http.get(url)
.map((response: Response) => <any>response.json())
.do(data => console.log("All: " + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
products.component.ts
import { Component, OnInit } from '@angular/core';
import { CurrencyPipe } from "@angular/common";
import { ActivatedRoute, Params } from '@angular/router';
import { ProductsService } from '../Services/products.service';
import { IProducts } from '../Models/products';
import { Observable } from 'rxjs/Rx';
import { Global } from '../Shared/global';
import { Subscription } from "rxjs/Subscription";
@Component({
templateUrl: '/app/Components/products.component.html',
providers: [CurrencyPipe]
})
export class ProductsComponent implements OnInit {
id: any;
products: IProducts[];
product: IProducts;
msg: string;
indLoading: boolean = false;
constructor(
private route: ActivatedRoute,
private _productsService: ProductsService) {
console.log(this.route.snapshot.params) // I see the params contains the kvp {'sectionID': 4} but it's just not passing through
}
ngOnInit(): void {
this.id = this.route.snapshot.params; //same as above, right side shows value, left side shows undefined
this.LoadProducts();
}
LoadProducts(): void {
this.indLoading = true;
this._productsService.get(Global.BASE_PRODUCT_ENDPOINT + this.id) // undefined gets passed, as expected but not as it should
.subscribe(products => { this.products = products; this.indLoading = false; },
error => this.msg = <any>error)
}
}
globals.ts
export class Global {
public static BASE_POST_ENDPOINT = 'api/postsapi/';
public static BASE_PRODUCT_ENDPOINT = 'api/productsapi/';
}
我试过将对象转换为字符串,但没有成功。我尝试了以下排列:
this.route.paramMap.subscribe(...)
this.route.params.url
this.route.params['sectionID']
this.route.params[0]
this.route.params[0]['sectionID']
这里一定有一些简单的东西我想念,但我的脑袋现在已经完成了。实在想不通。
由于您看到的是 params
中的值,请尝试更改 ngOnInit()
中的这一行
this.id = this.route.snapshot.params;
到
this.id = this.route.snapshot.params.get('sectionID');
// if you want the result to be a string,
// then you will likely have to add 'toString()' to above like,
// this.route.snapshot.params.get('sectionID').toString()
试一试吧,如果没有复制品,我自己很难检查出来。希望它有所帮助和有效。
好的,我知道问题出在哪里了。
当我转到 /products/
时,应用程序调用 /api/productsapi/
时没有任何额外参数,并按预期收到 JSON 响应。
例如当URL变为/products/7
时,预期的url: string
为/api/productsapi/7
或/api/productsapi/?0=7
我发现当我尝试导航到具有该 ID 的项目时,应用调用了错误的 API 地址。它正在从 /products/api/productsapi/?0=7
请求数据
巨大的捂脸时刻。
修复只有四个点。
global.ts
export class Global {
public static BASE_POST_ENDPOINT = '../api/postsapi/'; //ughhh
public static BASE_PRODUCT_ENDPOINT = '../api/productsapi/'; //double uggghh
}
当我不断收到臭名昭著的 Unexpected token < in JSON at position 0 ...
错误消息时,我应该知道 JSON 响应中存在某种问题。我猜是生活和学习。
基本上我试图从 url 段获取路由参数并将该参数传递给 API 调用。我可以在我的调试器中看到正在传递的值,但就在那时它传递给服务时它变得未定义。
我已经在这里待了几个小时了。我已经尝试了我能找到的每一个例子,但我仍然无法让它发挥作用。我真的可以为此使用一双新的眼睛。
出于本练习的目的,我导航到 /products/4
并且 API 端点应该是 /api/productsapi/4
以下是相关位:
app.routing.ts
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PostsComponent } from '../app/Components/posts.component';
import { HomeComponent } from '../app/Components/home.component';
import { ProductsComponent } from '../app/Components/products.component';
const appRoutes: Routes = [
{
path: 'home',
component: HomeComponent
},
{
path: 'posts',
component: PostsComponent
},
{
path: 'products',
children: [
{
path: '',
component: ProductsComponent
},
{
path: ':sectionID', //my first attempt at parameter routing... not very successful
component: ProductsComponent
},
{
path: '**',
redirectTo: 'products',
pathMatch: 'full'
}
]
},
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
}
];
export const
routing: ModuleWithProviders =
RouterModule.forRoot(appRoutes);
products.service.ts
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
@Injectable()
export class ProductsService {
constructor(private _http: Http) { }
get(url: string): Observable<any> { //url always ends up as api/productsapi/undefined
return this._http.get(url)
.map((response: Response) => <any>response.json())
.do(data => console.log("All: " + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
products.component.ts
import { Component, OnInit } from '@angular/core';
import { CurrencyPipe } from "@angular/common";
import { ActivatedRoute, Params } from '@angular/router';
import { ProductsService } from '../Services/products.service';
import { IProducts } from '../Models/products';
import { Observable } from 'rxjs/Rx';
import { Global } from '../Shared/global';
import { Subscription } from "rxjs/Subscription";
@Component({
templateUrl: '/app/Components/products.component.html',
providers: [CurrencyPipe]
})
export class ProductsComponent implements OnInit {
id: any;
products: IProducts[];
product: IProducts;
msg: string;
indLoading: boolean = false;
constructor(
private route: ActivatedRoute,
private _productsService: ProductsService) {
console.log(this.route.snapshot.params) // I see the params contains the kvp {'sectionID': 4} but it's just not passing through
}
ngOnInit(): void {
this.id = this.route.snapshot.params; //same as above, right side shows value, left side shows undefined
this.LoadProducts();
}
LoadProducts(): void {
this.indLoading = true;
this._productsService.get(Global.BASE_PRODUCT_ENDPOINT + this.id) // undefined gets passed, as expected but not as it should
.subscribe(products => { this.products = products; this.indLoading = false; },
error => this.msg = <any>error)
}
}
globals.ts
export class Global {
public static BASE_POST_ENDPOINT = 'api/postsapi/';
public static BASE_PRODUCT_ENDPOINT = 'api/productsapi/';
}
我试过将对象转换为字符串,但没有成功。我尝试了以下排列:
this.route.paramMap.subscribe(...)
this.route.params.url
this.route.params['sectionID']
this.route.params[0]
this.route.params[0]['sectionID']
这里一定有一些简单的东西我想念,但我的脑袋现在已经完成了。实在想不通。
由于您看到的是 params
中的值,请尝试更改 ngOnInit()
this.id = this.route.snapshot.params;
到
this.id = this.route.snapshot.params.get('sectionID');
// if you want the result to be a string,
// then you will likely have to add 'toString()' to above like,
// this.route.snapshot.params.get('sectionID').toString()
试一试吧,如果没有复制品,我自己很难检查出来。希望它有所帮助和有效。
好的,我知道问题出在哪里了。
当我转到 /products/
时,应用程序调用 /api/productsapi/
时没有任何额外参数,并按预期收到 JSON 响应。
例如当URL变为/products/7
时,预期的url: string
为/api/productsapi/7
或/api/productsapi/?0=7
我发现当我尝试导航到具有该 ID 的项目时,应用调用了错误的 API 地址。它正在从 /products/api/productsapi/?0=7
巨大的捂脸时刻。
修复只有四个点。
global.ts
export class Global {
public static BASE_POST_ENDPOINT = '../api/postsapi/'; //ughhh
public static BASE_PRODUCT_ENDPOINT = '../api/productsapi/'; //double uggghh
}
当我不断收到臭名昭著的 Unexpected token < in JSON at position 0 ...
错误消息时,我应该知道 JSON 响应中存在某种问题。我猜是生活和学习。