2017-05-05 170 views
2

我想通過url從特定產品中檢索id。這是到目前爲止我的代碼:Angular 2/ASP.NET Core從URL中檢索ID

進口

//Imports from @Angular 
import { Component, OnInit } from '@angular/core'; 
import { RouterModule, Router, Params, RouterLink, ActivatedRoute } from '@angular/router'; 
import { Http } from '@angular/http'; 

構造

constructor(
     private _hatListService: HatListService, private _router: Router, private _params: ActivatedRoute) { 

    } 

帽子editor.component ngOnInit

ngOnInit() { 

      this._params.params.subscribe((params: Params) => { 
     var id = params['id'] * 1;//*1 efter det som man vill parse:s so bilr det som int.parse 

     this._hatListService.getHat(this.id).subscribe(

      foundHats => this.thisHatModel = foundHats); 
     console.log(this.thisHatModel) 
    }); 

} 

服務

public _getHatById: string = '/api/Hats/GetHatById'; 

     getHat(id: number): Observable<Hat> { 
      //debugger 
      return this._http.get(this._getHatById + '/' + id).map(res => <Hat>res.json()).catch(this.handleError); 


     } 

控制器

// GET: api/Hats/5 
    [HttpGet("GetHatById/{id}")] 
    public async Task<IActionResult> GetHat([FromRoute] int id) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     var hat = await _context.Hat.SingleOrDefaultAsync(m => m.Id == id); 

     if (hat == null) 
     { 
      return NotFound(); 
     } 

     return Ok(hat); 
    } 

當我將鼠標懸停在每個產品的URL產生:

enter image description here

但是當我點擊該產品的ID不能從瀏覽器抓:

enter image description here

位指示:

enter image description here

我猜的錯誤在此行中我getHat發生( ) 方法。在* 1是鑄造將ID號:

>  this._params.params.subscribe((params: Params) => { 
      var id = params['id'] * 1; 

     }); 

我試過Angualr.io exapmlpe但不能讓它爲我工作。 感謝名單所有幫助

回答

1

解決它改變了這種:

變種ID =參數[ 'ID'] * 1;

到:

公共ID:任;

this.id = params ['id'] * 1;

它工作。