2017-10-03 1 views
0

Grundsätzlich versuche ich einen Route-Parameter aus dem URL-Segment und übergeben Sie diesen Parameter an den API-Aufruf. Ich kann in meinem Debugger den übergebenen Wert sehen, aber zu diesem Zeitpunkt wird er an den Dienst übergeben, der nicht definiert wird.Angular 2 Route Params Wert als undefined übergeben

Ich bin schon seit Stunden hier. Ich habe jedes Beispiel ausprobiert, das ich finden kann, und ich kann es immer noch nicht zur Arbeit bringen. Ich könnte wirklich ein frisches Paar Augen dafür verwenden. Für den Zweck dieser Übung, ich bin die Navigation zu /products/4 und die API-Endpunkt soll /api/productsapi/4

Hier werden die entsprechenden Bits sein:

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

Ich habe versucht, das Objekt in String zu konvertieren, und das hat nicht funktioniert. Ich habe versucht, aus den folgenden Permutationen:

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

Es einfach etwas sein muss, bin ich hier fehlt, aber mein Kopf ist in jetzt getan. Kann nicht wirklich denken.

Antwort

0

In Ordnung, ich habe herausgefunden, was das Problem war. Wenn ich zu /products/ gehe, ruft die App /api/productsapi/ ohne zusätzliche Parameter auf und empfängt eine JSON-Antwort wie erwartet.

Wenn die URL Änderungen /products/7 zum Beispiel, sind die erwarteten url: string/api/productsapi/7 oder /api/productsapi/?0=7

Ich fand heraus, dass, wenn ich versuche, mit der ID zu dem Punkt zu navigieren, die App der falsche API-Adresse aufrufen. Es fordert Daten von /products/api/productsapi/?0=7

Massive Facepalm Moment.

Die Lösung war nur vier Punkte.

global.ts

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

I clued in sein soll, dass es ein Problem in der JSON-Antwort irgendwie war, als ich hielt die berüchtigte Unexpected token < in JSON at position 0 ... Fehlermeldung bekommen. Lebe und lerne, denke ich.

0

Da Sie die Werte in params sehen, versuchen Sie diese Zeile in ngOnInit() Ändern

this.id = this.route.snapshot.params; 

zu

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

einfach, es zu versuchen, da es schwierig ist, es selbst zu überprüfen, ohne ein Reproduktion. Hoffe es hilft und arbeitet.

+0

Leider funktioniert es nicht.Ich erhalte diesen Fehler, wenn ich den obigen Code verwende: ERROR TypeError: this.route.snapshot.params.get ist keine Funktion –