Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Angular 2 Http Get not returning data from WebAPI Controller

$
0
0

Have I used the right code to call a WebAPI Controller?

app.components.ts

import { Inject, Component } from 'angular2/core';
import { DataService } from './data.service';
import { HTTP_BINDINGS } from 'angular2/http';

@Component({ 
    selector: 'app',
    bindings: [DataService, HTTP_BINDINGS],
    template: `<h1>Hello World</h1><li *ngFor="#item of items"><span>{{item.Name}}</span> </li>
`
})
export class AppComponent {
    private items: any[];
    constructor( @Inject(DataService) public dataService: DataService) {
        this.dataService = dataService;
    }


    ngOnInit() {
        this.dataService.getItems()
            .subscribe((items: any[]) => {
                this.items = items;
            }); 
    }
}

data.Service.ts

import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import 'rxjs/add/operator/map';

@Injectable()
export class DataService {
    private http: Http;
    constructor(http: Http) {
        this.http = http;
    }

    getItems() {
        return this.http.get('/api/todo')
            .map((res: Response) => res.json());
    }

}

Controller:

    [Route("api/[controller]")]
    public class TodoController : Controller
    {
        [FromServices]
        public ITodoRepository TodoItems { get; set; }

        [HttpGet]
        public IEnumerable<TodoItem> GetAll()
        {
            return TodoItems.GetAll().OrderBy(x=>x.Name);
        }

....


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>