在Angular 7中调用ASP.NET Web API两次的解决方法如下:
api.service.ts
的服务文件,用于处理与Web API的通信。import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private apiUrl = 'https://your-web-api-url';
constructor(private http: HttpClient) { }
getData(): Observable {
return this.http.get(`${this.apiUrl}/data`);
}
}
ApiService
来调用Web API。import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-example',
template: `
{{ data }}
`,
})
export class ExampleComponent implements OnInit {
data: any;
constructor(private apiService: ApiService) { }
ngOnInit() {
}
getData() {
this.apiService.getData().subscribe(
response => {
this.data = response;
},
error => {
console.log(error);
}
);
}
}
ApiService
。import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-example2',
template: `
{{ data }}
`,
})
export class Example2Component implements OnInit {
data: any;
constructor(private apiService: ApiService) { }
ngOnInit() {
}
getData() {
this.apiService.getData().subscribe(
response => {
this.data = response;
},
error => {
console.log(error);
}
);
}
}
这样,无论你在任何组件中调用getData()
方法,都可以正确地调用Web API,并且不会发生调用两次的问题。