如何解决通过HTTPGET将Angular Observable传递给ASP MVC
在HTML上,当您单击下面的 exportok()按钮时,我希望通过选定的下拉菜单将当前年份(aka.2020)发送到名为EXPORT的.NET MVC Controller函数,方法是通过HTTPGET调用"/api/stations/export”.
Admin.component.ts
exportyears = [
{name: '1 July 2019 to 30 June 2020',id: '2019-2020'},{name: '1 July 2020 to 30 June 2021',id: '2020-2021'},];
Admin.component.html
<form>
<select formControlName="exportyear" [(ngModel)]="reportyear"(change)="onClickMe()">
<option
*ngFor="let exportyear of exportyears" [ngValue]="exportyears"
>
{{ exportyear.id }}
</option>
</select>
</form>
<button class="btn btn-primary" type="button" (click)="exportOk(exportyears[0].id)">
<i class="glyphicon glyphicon-ok"></i> OK</button>
Service.ts
export(reportyear: string): Observable<Response> {
// let headers = new Headers();
// headers.append('Content-Type','application/json');
// headers.append('reportyear',reportyear);
let request = new Request({
method: RequestMethod.Get,url: environment.baseUrl + "/api/stations/export",responseType: ResponseContentType.Blob,body: {reportyear}
}
);
Station.ts
exportOk(reportyear: string) {
this.exporting = true;
this.exportMessage = null;
this.stationsService.export(reportyear)
.subscribe(
(res: Response) => {
this.exporting = false;
this.exportModal.hide();
Utils.launchAttachment(res);
},error => {
this.exporting = false;
if (error.error) {
this.exportMessage = error.error;
}
else {
this.exportMessage = error;
}
}
);
ASP.NET MVC控制器 Controller.cs
[HttpGet("export")]
public async Task<IActionResult> Export([FromBody]string reportyear)
{
var obj = reportyear; //show me the year so I can use it further down the line…..
var stations = await stationRepository.GetExportAsync();
......
}
解决方法
我有类似的东西,可能会对您有所帮助。
/// <summary>
/// Find a product by name
/// </summary>
/// <param name="Name"></param>
/// <returns></returns>
[HttpGet("{name}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetByName(string name)
{
try
{
var item = await _productService.GetOneByName(name);
if (item != null)
{
return Ok(item);
}
return NotFound();
}
catch (System.Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError,ex.Message.ToJson());
}
}
您可以看到大括号[HttpGet(“ {name}”)]中的内容与函数参数GetByName(string name)中的内容匹配。顺便说一句,我建议您使用Postman调试api。
更新
试试这个:
export(reportyear: string): Observable<Response> {
let request = new Request(
{
method: RequestMethod.Get,url: environment.baseUrl + "/api/stations/export" + "/" + reportyear,responseType: ResponseContentType.Blob
}
);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。