Rumah  >  Artikel  >  hujung hadapan web  >  Angular2 http服务的详情介绍。2018最新的angularjs2服务介绍详情

Angular2 http服务的详情介绍。2018最新的angularjs2服务介绍详情

寻∝梦
寻∝梦asal
2018-09-07 14:28:37943semak imbas

angular2的http服务是用于从后台程序获取或更新数据的一种机制,通常情况我们需要将与后台交换数据的模块做出angular服务,利用http获取更新后台数据,angular使用http的get或put进行后台调用采用的是ajax方式,跨域问题需要单独处理。下面来看一个例子,演示从后台web api中获取数据并进行页面加载。

1、由于要使用http服务,所以我们一定要在我们的web页面需要引入3f148f16a92f71b127090237c998858c2cacc6d41bbb37262a98f745aa00fbf0,这步很关键,我之前发生的找不到http服务的原因就在此,浪费了很多时间在此。
2、在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]);

3、创建服务

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

4、服务调用

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;
constructor(private _appService: appService,private _channelService:channelService) {  
this.getWebTitle();
}
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/42820a3cc9b8dae7922d3e053756785d
public IEnumerableb79328fbba81c10bf446ccf392e511f9 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

本篇文章到这就结束了。  (想看更多就到PHP中文网angularjs学习手册中学习)有问题的可以下方提问。


Atas ialah kandungan terperinci Angular2 http服务的详情介绍。2018最新的angularjs2服务介绍详情. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn