Angular 6 : call API in Angular
Countrydetail class
export class CountryDetail {
CountryId: number;
CountryName: string;
}
country.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../../environments/environment';
@Injectable()
export class CountryDetailService {
private httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8'
}),
};
constructor(private http: HttpClient) {
}
async getCountryDetail(countryId: number): Promise<CountryDetail> {
let request = this.http.post(environment.apiUrl + environment.countrydetailurl, { data: {CountryId: countryId} }, this.httpOptions).
toPromise().
then(res => {
return res["d"] as CountryDetail;
}).
catch(err => {
console.log(err);
return null;
});
let result = await request;
return result;
}
}
country.component.ts
export class CountryComponent implements OnInit {
spinnerService: any;
public detail = new CountryDetail();
showSpinner: boolean = true;
constructor(private countryDetailService: CountryDetailService, private router: Router,
private route: ActivatedRoute) {
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
}
}
async ngOnInit() {
const productId = +this.route.snapshot.queryParamMap.get('id');
let data = await this.countryDetailService.getCountryDetail(productId);
this.detail = data as CountryDetail;
this.showSpinner = false;
}
}
country.component.html
<table>
<tr *ngFor="let country of detail">
<td>country.CountryName</td>
<td><a href="/detail/country.CountryId">Detail</a></td>
</tr>
</table>
Hope this will help you and save your time.
Enjoy !!!
:)