Search code examples
angularangular-router

Angular 2 route params value passed as undefined


Basically I am trying to get a route parameter from the url segment and pass that parameter to the API call. I can see in my debugger the value being passed but right at that point it passes to the service it becomes undefined.

I have been at this for hours now. I've tried every example I can find and I still can't get this to work. I could really use a fresh pair of eyes for this. For the purpose of this exercise, I am navigating to /products/4 and the API endpoint is supposed to be /api/productsapi/4

Here are the relevant bits:

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/';
}

I've tried converting the object to string and that didn't work. I tried out the following permutations:

    this.route.paramMap.subscribe(...)
    this.route.params.url
    this.route.params['sectionID']
    this.route.params[0]
    this.route.params[0]['sectionID']

There must be something simple here I am missing, but my head is done in now. Cannot really think.


Solution

  • Alright, I figured out what was the problem.

    When I go to /products/ the app calls the /api/productsapi/ without any extra parameters and receives a JSON response as expected.

    When the URL changes to /products/7 for example, the expected url: string is /api/productsapi/7 or /api/productsapi/?0=7

    I found out that when I try to navigate to the item with the id, the app calls the wrong API address. It's requesting data from /products/api/productsapi/?0=7

    Massive facepalm moment.

    The fix was just four dots.

    global.ts

    export class Global {
        public static BASE_POST_ENDPOINT = '../api/postsapi/'; //ughhh
        public static BASE_PRODUCT_ENDPOINT = '../api/productsapi/'; //double uggghh 
    }
    

    I should have been clued in that there was a problem in the JSON response somehow when I kept getting the infamous Unexpected token < in JSON at position 0 ... error message. Live and learn I guess.