angularjs2 学习笔记(五) http服务

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';node

import {myFrame} from "./frame/component/myFrame.component";web

import 'rxjs/Rx';ajax

 

bootstrap(myFrame, [ HTTP_PROVIDERS]);json

三、建立服务

///<reference path="../../../node_modules/angular2/typings/browser.d.ts"/>bootstrap

 

import {Injectable} from 'angular2/core';后端

import {Http } from 'angular2/http';api

 

@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()

四、服务调用

///<reference path="../../../node_modules/angular2/typings/browser.d.ts"/>

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转换为咱们前端使用的model

Web api:

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

 

学习到这里了,逐步开始向实际应用转换,中间的每一步都是血泪史。