Web
Analytics
angular 4 with asp.net core 2 and WEB API | REST services | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

In this tutorial and demonstrating that how we can create angular 4 project using Web API first task is to create Web API using Visual Studio and copy the address of running Web API which will be used later.





 

Code for enabling cors in web API

  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods"
           value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>

 

 

Step 1: Create a project using the angular template in visual studio 2017.

Step 2: Create new Service(myhttpservice.service.ts)

import { Injectable } from '@angular/core';
import { Http, HttpModule } from '@angular/http'

@Injectable()
export class HelloWorldService {
    constructor(private _http: Http) { }
    getdata() {
        return this._http.get('http://localhost:56286/api/values');
    }
}

 

Step3: Add following code to app.component.ts

import { HelloWorldService } from '../myhttpservice.service';
import { Component, OnInit } from '@angular/core';


@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [HelloWorldService]
})
export class AppComponent implements OnInit {
    constructor(private service: HelloWorldService) { }
    ngOnInit() {
        this.service.getdata().subscribe(
            datas => console.log(datas.json())
            )
    }
}

Step 4: Run Your project

ASP.NET Core 2.0 Online Training

ASP.NET Core 2.0 Online Training