2017-10-03 11 views
0

基本的に、私はURLセグメントからルートパラメータを取得し、そのパラメータをAPI呼び出しに渡そうとしています。私は私のデバッガで渡されている値を見ることができますが、その時点でそれは未定義となるサービスに渡されます。角度2のルートパラメータ値が未定義として渡されました

私は今数時間この状態にいました。私は見つけることができるすべての例を試しましたが、私はまだこれを動作させることができません。私は本当にこれのために目を新鮮なペアを使用することができます。 は、この演習の目的のために、私は/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/'; 
} 

オブジェクトを文字列に変換しようとしましたが、動作しませんでした。私は次の順列を試しました:

私は行方不明ですが、私の頭は今行われています。本当に考えることはできません。

答えて

0

申し訳ありませんが、私は問題が何かを考え出しました。

私が/products/に行くと、アプリは余分なパラメータを使わずに/api/productsapi/を呼び出し、期待通りにJSON応答を受け取ります。

例えば/products/7へのURLの変更を、予想url: stringは私がidを持つアイテムに移動しようとすると、アプリは間違ったAPIアドレスを呼び出すことが判明/api/productsapi/7または/api/productsapi/?0=7

です。データをリクエストしています/products/api/productsapi/?0=7

大顔の瞬間です。

修正はわずか4ドットでした。

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レスポンスにあったということでcluedされている必要があります。生きて、私が推測することを学ぶ。

0

あなたは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() 

ngOnInit()

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

にこの行を変更してみてください再生。それが助けられ、働くことを望みます。

+0

残念ながら、それは機能しません。私は上記のコードを使用するとこのエラーが発生します:エラーTypeError:this.route.snapshot.params.getは関数ではありません –