Angular 2 route params值作为undefined传递

时间:2017-10-03 21:46:49

标签: angular angular-router

基本上我试图从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']

我必须在这里找到一些简单的东西,但我现在已经完成了。真的不能想。

2 个答案:

答案 0 :(得分:0)

由于您看到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()

试一试,因为很难在没有复制品的情况下自行查看。希望它有所帮助。

答案 1 :(得分:0)

好吧,我想出了问题所在。

当我转到/products/时,应用会在没有任何额外参数的情况下调用/api/productsapi/并按预期收到JSON响应。

例如,当网址更改为/products/7时,预期的url: string/api/productsapi/7/api/productsapi/?0=7

我发现当我尝试导航到带有ID的项目时,应用会调用错误的API地址。它从/products/api/productsapi/?0=7

请求数据

巨大的facepalm时刻。

修复只有四个点。

  

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响应中出现了问题。我猜是生活和学习。