Answer the question
In order to leave comments, you need to log in
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++;
}
}
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));
}
}
int x = 0;
[HttpGet("[action]")]
public int Increment()
{
return ++x;
}
Answer the question
In order to leave comments, you need to log in
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));
// а вообще, для инкапсуляции запросов лучше использовать сервисы
}
}
<button (click)="Increment()"></button>
Или на любой другой тег
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 questionAsk a Question
731 491 924 answers to any question