C
C
Carsberg2017-11-04 11:57:28
Angular
Carsberg, 2017-11-04 11:57:28

How to get data from asp net core controller in angular 2?

Hello, I decided to figure out how asp.net core 2 works in conjunction with Angular 2, created a project in the studio and began to disassemble the standard template with 3 pages: home, Counter and Fetch Data. And here with the second it is not absolutely clear. Initially, there is a purely front-line, as I understand it, increment:

export class CounterComponent {
    public currentCount = 0;

    public incrementCounter() {
        this.currentCount++;
    }
}

It became interesting to me, but how can I make this increment on the server, i.e. through the controller. I took the code from FetchDataComponent and inserted it into CounterComponent, it turned out like this:
export class CounterComponent {
    public currentCount = 0;

    constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
        http.get(baseUrl + 'api/SampleData/Increment').subscribe(result => {
            this.currentCount = result.json();
        }, error => console.error(error));
    }
}

and added an action in the controller:
int x = 0;
[HttpGet("[action]")]
        public int Increment()
        {
            return ++x;
        }

It seems to work, but the value "1" is pulled up when switching to a window with an increment (it's understandable, apparently because of the constructor). But I didn’t understand how I can attach an action call to the button so that it returns a value increased by 1? Something went wrong. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2017-11-04
@Carsberg

At the front, in the CounterComponent class, create a method where the desired action will occur when the button is pressed:

export class CounterComponent {
    public currentCount = 0;

    constructor(private http: Http, @Inject('BASE_URL') private baseUrl: string) { }

    Increment(){
        this.http.get(this.baseUrl + 'api/SampleData/Increment').subscribe(result => {
            this.currentCount = result.json().value;
        }, error => console.error(error));
        // а вообще, для инкапсуляции запросов лучше использовать сервисы
    }
}

Then hang this handler method on the click event:
<button (click)="Increment()"></button>
Или на любой другой тег

In an action, I would recommend always using objects, at least anonymous ones:
static int x = 0; // здесь нужен static, иначе всегда будешь получать в ответе число 1
[HttpGet("[action]")]
public IActionResult Increment()
{
     x++;
     return Ok(new {
         value = x
     });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question