AnswerBun.com

Pass Angular Observable to ASP MVC via HTTPGET

Stack Overflow Asked on September 8, 2020

On the HTML, when you click the exportok() button below, I wish to send the current year (aka.2020) from the selected dropdown to the.NET MVC Controller function called EXPORT via a HTTPGET call "/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>&nbsp;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
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();
    ......
  }

One Answer

I have something like this, it may help you.

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

you can see that what is in the curly brackets [HttpGet("{name}")] matches what is in the function parameters GetByName(string name). Btw, I suggest you to use postman for debugging your api if you don't.

UPDATE
try this:

export(reportyear: string): Observable<Response> {

let request = new Request(
   {
      method: RequestMethod.Get,
      url: environment.baseUrl + "/api/stations/export" + "/" + reportyear,
      responseType: ResponseContentType.Blob
   }
);

Correct answer by Sinan on September 8, 2020

Add your own answers!

Related Questions

std::map::operator[] is more efficient than std::map::insert?

1  Asked on December 27, 2020 by eddieipeace

   

Splitting a list (?)

1  Asked on December 27, 2020 by superannuated

   

Python Scrapy how to save data in different files

1  Asked on December 27, 2020 by silver-flash

   

JS get random value from array and update array

2  Asked on December 27, 2020 by nicolas-schmit

     

Caught and declared exception in Java?

1  Asked on December 26, 2020 by hrvoje-t

   

IEnumerable and Recursion using yield return

8  Asked on December 26, 2020 by jamie-dixon

       

How to parse CSV with node.js?

2  Asked on December 26, 2020 by idarosa

         

Why this program with for loop give zero when y>5 and x=2

2  Asked on December 26, 2020 by vms

 

Null pointer exception. How my connection object is pointing to null

2  Asked on December 26, 2020 by monisha-ravi

     

How do I make contents in HTML by using css

0  Asked on December 26, 2020 by jaeseo-lee

   

How to show Toaster after logout

2  Asked on December 26, 2020

   

How to write to a csv within a pandas UDF in pyspark?

0  Asked on December 26, 2020 by codemaster2020

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir