如何将id发送到get方法

时间:2016-07-30 16:15:53

标签: angular angular2-routing

我正在尝试通过ActivatedRoute获取新闻ID的快照,以便稍后我可以将该ID传递给服务中的方法,该服务通过api路由请求该特定新闻ID。

这是我的组成部分:

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);
      });
  }

}

这是我的服务:

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);
      });
  }

}

可悲的是,我在ts中的组件中出现了这个错误:类型'{[key:string]中不存在属性'id':any; }”。

谢谢!

1 个答案:

答案 0 :(得分:0)

this.route.snapshot.params['id']这样您就可以从snapshot获取ID。

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);
      });
}