locked
angular call to server RRS feed

  • Question

  • User2096382003 posted

    is it possible in angular to have a button in a template/component that will fire a call to a server side controller method?

    Monday, September 16, 2019 7:04 PM

All replies

  • User1634355159 posted

    Hi  mark-1961,

    In angular, you can use HttpClient to request data from the server.Below is the detailed official documentation.

    https://angular.io/tutorial/toh-pt6

    For a button in a template/component binding event, you can refer to the following document.

    https://angular.io/guide/user-input

    Here is an example  by using the .Net Core angular template in Visual Studio2019.

    HTML:

    <h1>Weather forecast</h1>
    
    <p>This component demonstrates fetching data from the server.</p>
    
    <p *ngIf="!forecasts"><em>Loading...</em></p>
    <button (click)="onClickMe()">Click me!</button>
    <table class='table table-striped' *ngIf="forecasts">
      <thead>
        <tr>
          <th>Date</th>
          <th>Temp. (C)</th>
          <th>Temp. (F)</th>
          <th>Summary</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let forecast of forecasts">
          <td>{{ forecast.dateFormatted }}</td>
          <td>{{ forecast.temperatureC }}</td>
          <td>{{ forecast.temperatureF }}</td>
          <td>{{ forecast.summary }}</td>
        </tr>
      </tbody>
    </table>

    ts file:

    import { Component, Inject } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Component({
      selector: 'app-fetch-data',
      templateUrl: './fetch-data.component.html'
    })
    export class FetchDataComponent {
      public forecasts: WeatherForecast[];
    
      constructor(private http: HttpClient, @Inject('BASE_URL')  baseUrl: string) {
        
      }
    
      onClickMe() {
        this.http.get<WeatherForecast[]>('api/SampleData/WeatherForecasts').subscribe(result => {
          this.forecasts = result;
        }, error => console.error(error));
      }
    }
    
    interface WeatherForecast {
      dateFormatted: string;
      temperatureC: number;
      temperatureF: number;
      summary: string;
    }

    Best Regards ,

    Lewis Lu

    Tuesday, September 17, 2019 7:22 AM