My angular 4 doesn't hit my API in my controller
ApiService
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import { ICompany } from './ICompany';
import { HeaderService } from '/shared/header.service';
@Injectable()
export class CompanyService {
privatecompanyUrl='api/companies';
privateheaders:HttpHeaders;
constructor(privatehttp:HttpClient, privateheaderService:HeaderService) {
this.headers=newHttpHeaders({ 'Content-Type':'application/json' });
}
getCompanies():Observable<ICompany[]> {
consturl=`${this.companyUrl}/GetCompanies`;
returnthis.http.get(url, { headers:this.headers })
.do(data => console.log('All: ' + JSON.stringify(data)))
}
}?
My Component that will consume my service
ngOnInit() {
this.getCompanies();
}
getCompanies():void {
this.companyService.getCompanies()
.subscribe(companies => {
this.companies=companies;
},
error=>this.errorMessage= <any>error
);
}?
[HttpGet]
[Route("api/Companies/GetCompanies")]
public IEnumerable<Company> GetCompanies()
{
List<Company> companies = new List<Company>();
for (int x = 1; x < 5; x++)
{
companies.Add(new Company
{
Id = x,
Name = "Company " + x,
Address = "Address " + x,
ContactInfo = "ContactInfo " + x,
TinNumber = "Tin Number " + x
});
}
return companies;
}
I tried to Call Web API using Angular 4 and httpclient module and I was able to call it, here is the image of debug output
Here is the article which I referred
http://www.encodedna.com/angular/httpclient-service-in-angular-4-with-web-api-in-aspdotnet-mvc-4.htm
If your issue is still there, you can upload your Angular project on GitHub or on google drive and paste the link so I can download it and test locally, thanks
@vikas_jk
I fixed the problem by removing these lines of code on my webconfig.
-------------------
<!--<system.webServer>
<rewrite>
<rules>
<rule name="Angular Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />--><!--Base href in index.cshtml--><!--
</rule>
</rules>
</rewrite>
</system.webServer>-->
-------------------
I added these codes to refresh my website . It came from angular.io.
Now, my problem on my refresh comes back. I guess I need to research again for other alternative. I also tried the link you provided, but I believe the the line of codes that i uncommented is the real problem.
Thank you Mr. Vikas.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly