2016-07-30 7 views
0

Ich versuche, eine Momentaufnahme einer News-ID durch ActivatedRoute zu bekommen, damit ich später diese ID an eine Methode in einem Dienst übergeben kann, die über eine API-Route nach dieser bestimmten News-ID fragt .So senden Sie eine ID an eine Get-Methode

Dies ist meine Komponente:

import { Component, OnInit } from '@angular/core'; 
import { ApiNoticiasService } from './api-noticias.service'; 
import { ActivatedRoute } from '@angular/router'; 

@Component({ 
    moduleId: module.id, 
    selector: 'app-editar-noticias', 
    templateUrl: 'editar-noticias.component.html', 
    styleUrls: ['editar-noticias.component.css'], 
    providers: [ApiNoticiasService] 
}) 
export class EditarNoticiasComponent implements OnInit { 
    noticia: any; 

    constructor(
    private route: ActivatedRoute, 
    private _apiNoticias: ApiNoticiasService) { } 

    ngOnInit() { 
    this._apiNoticias.getNoticia(this.route.snapshot.params.id) 
     .then((noticia) => this.noticia = noticia) 
     .catch((err) => { 
     console.log(err); 
     }); 
    } 

} 

Und das ist mein Service:

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 

import { Observable } from 'rxjs/Rx'; 

@Injectable() 
export class ApiNoticiasService { 
    constructor(private _http: Http) { } 

    getNoticia(id) { 
    return this._http.get('http://localhost:3000/noticia/:id') 
     .map((response: Response) => response.json()) 
     .toPromise() 
     .catch((err: any) => { 
     console.log(err); 
     return Promise.reject(err); 
     }); 
    } 

} 

Leider bekomme ich diesen Fehler in meiner Komponente von ts: Property 'id' existiert nicht auf Art '{[key: string]: beliebig; } '.

Danke!

Antwort

0

this.route.snapshot.params['id'] So erhalten Sie ID von snapshot.

ngOnInit() { 
    this._apiNoticias.getNoticia(+this.route.snapshot.params['id']) //<---this way you get id. + sign will convert it to number. 
     .then((noticia) => this.noticia = noticia) 
     .catch((err) => { 
     console.log(err); 
     }); 
} 

getNoticia(id:number) { 
    return this._http.get('http://localhost:3000/noticia/:'+ id) //<----changed it. 
     .map((response: Response) => response.json()) 
     .toPromise() 
     .catch((err: any) => { 
     console.log(err); 
     return Promise.reject(err); 
     }); 
} 
+1

Arbeitete groß, danke! – cerealex

Verwandte Themen