Call web API controller using Angular 2

前端 未结 2 1056
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 00:24

I am new to Angular2. I want to call an API using Angular2 in my MVC6 project. I have tried many things (including the guide at Angular2 calling ASP.NET Web API) without suc

2条回答
  •  礼貌的吻别
    2020-12-24 01:18

    This is how I did it my application (angular2 as front-end with Web API core)-

    1. Create a controller using entity framework which provides all actions - GET, POST, PUT and DELETE. Refer this link in case you are new to web api and entity framework - https://docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html

    2. Enabled CORS in Web API

    [This is done to handle cross communication from localhost:3000 (angular2) to localhost:59024 (webapi)]

    First, add dependency in project.json - "Microsoft.AspNetCore.Cors": "1.0.0",

    then enable CORS in startup.cs like this-

    app.UseCors(builder => {
        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
    });
    

    You can find more information about CORS here - https://docs.asp.net/en/latest/security/cors.html

    3.In Angular2 front-end, you can write your service component like this-

    @Injectable()
    export class WebApiService {
    
        private _webApiUrl = 'http://localhost:59024/api/EmployeeMastersAPI'; 
    
            constructor(private _http: Http) { 
    
            }
    
        getEmployees(): Observable<{}> {
            return this._http.get(this._webApiUrl)
                .map((response: Response) =>  response.json())
                 .do(data => console.log('All: ' +  JSON.stringify(data)))
                 .catch(this.handleError)
                ;
        }
    
        getEmployee(id: number): Observable {
            return this.getEmployees()
                .map((emp: IEmployee[]) => emp.find(p => p.EMPID === id));
        }
    
        addEmployeesDetails(emp) {
            var headers = new Headers();
            headers.append('Content-Type', 'application/json; charset=utf-8');
            console.log('add emp : ' +  JSON.stringify(emp));
            this._http.post(this._webApiUrl, JSON.stringify(emp), { headers: headers }).subscribe();
    
        }
    
        private handleError(error: Response) {
            console.error(error);
            return Observable.throw(error.json().error || 'Server error');
        }
    
    }
    

    See if this helps.

提交回复
热议问题