angular2的http服務是用於從後臺程序獲取或更新數據的一種機制,一般狀況咱們須要將與後臺交換數據的模塊作出angular服務,利用http獲取更新後臺數據,angular使用http的get或put進行後臺調用採用的是ajax方式,跨域問題須要單獨處理。下面來看一個例子,演示從後臺web api中獲取數據並進行頁面加載。html
一、因爲要使用http服務,因此咱們必定要在咱們的web頁面須要引入<script src="node_modules/angular2/bundles/http.dev.js"></script>
,這步很關鍵,我以前發生的找不到http
服務的緣由就在此,浪費了不少時間在此。
二、在angular
入口還需引入HTTP_PROVIDERS
,並注入,同時因爲要使用map,subscribe等因此須要使用rxjs
庫,那麼就須要提早在入口程序中引入import 'rxjs/Rx'
,血的教訓前端
import {bootstrap} from 'angular2/platform/browser'; import {HTTP_PROVIDERS} from 'angular2/http'; import {myFrame} from "./frame/component/myFrame.component"; import 'rxjs/Rx'; bootstrap(myFrame, [ HTTP_PROVIDERS]);
import {Injectable} from 'angular2/core'; import {Http } from 'angular2/http'; @Injectable() export class channelService { private _carsUrl: string = "http://localhost:6611/api/Chanel"; constructor(private _http: Http) { } getChannelList() { return this._http.get(this._carsUrl).map(responce => responce.json()) } 在這個服務中使用了`http`中的`get`來獲取數據,這裏get的`url(web api)`是與我目前的`anuglar`應用在一個域內。做爲服務咱們須要申明該服務是可注入的`@Injectable()`
import {Component} from 'angular2/core'; import {appService} from './../service/appsetting.service' import {channelService} from './../service/channel.service' import {Channel} from './../model/channel' @Component({ selector: 'topNav', templateUrl: '../app/frame/template/topNav.html', providers: [appService, channelService] }) export class topNav { webTitle: string; public items: Channel[]; constructor(private _appService: appService,private _channelService:channelService) { this.getWebTitle(); this.getChannelList(); } getWebTitle() { this.webTitle = this._appService.AppSetting.webTitle; } getChannelList() { this._channelService.getChannelList().subscribe(res => { this.items=res}); } } 這裏就和普通服務調用沒什麼區別了,須要先import再在providers中申明,而後在構造函數中注入就好了。
這個例子中有個須要注意的是咱們前端model和後端model有可能不一致,那麼須要在獲取數據後再進行轉換,若是類型字段都一致那麼能夠直接使用,因爲是json格式,系統會自動將後臺model轉換爲咱們前端使用的modelnode
Web api:web
public class ChanelController : ApiController { // GET api/<controller> public IEnumerable<Chanel> Get() { return new Chanel[] { new Chanel{ ID="1", ChanelName="組織機構"},new Chanel{ ID="2",ChanelName="通知公告"} }; } } 注:web api 可使用Swashbuckle 進行測試,安裝 PM>Install-Package Swashbuckle,使用時只需在路徑後加入swagger,如http://localhost:6611/swagger/ui/index