Angular拥有自己的HTTP库,可以用于调用外部API。

在JavaScript世界里有三种方式可以实现异步请求,Callback,Promise与Observable。Angular倾向于使用Observable方式。

HTTP库属于Angular中独立的模块,这意味着当使用时需要导入它。

import {
// The NgModule for using @angular/http
HttpModule, // the class constants
Http,
Response,
RequestOptions,
Headers
} from '@angular/http';

举个基本的HTTP请求例子:

import { Component, OnInit } from '@angular/core';
import {Http, Response} from '@angular/http'; @Component({
selector: 'app-simple-http',
templateUrl: './simple-http.component.html'
})
export class SimpleHttpComponent implements OnInit {
data: Object;
loading: boolean; constructor(private http: Http) {
} ngOnInit() {
} makeRequest(): void {
this.loading = true;
this.http.request('http://jsonplaceholder.typicode.com/posts/1')
.subscribe((res: Response) => {
this.data = res.json();
this.loading = false;
});
}
}

http.request返回一个Observable,通过subscribe订阅变化。

如果是想要用GET方式请求API的话,可以使用HTTP库中的http.get方法。

@Injectable()
export class YouTubeSearchService {
constructor(private http: Http,
@Inject(YOUTUBE_API_KEY) private apiKey: string,
@Inject(YOUTUBE_API_URL) private apiUrl: string) {
} search(query: string): Observable<SearchResult[]> {
const params: string = [
`q=${query}`,
`key=${this.apiKey}`,
`part=snippet`,
`type=video`,
`maxResults=10`
].join('&');
const queryUrl = `${this.apiUrl}?${params}`;
return this.http.get(queryUrl)
.map((response: Response) => {
return (<any>response.json()).items.map(item => {
// console.log("raw item", item); // uncomment if you want to debug
return new SearchResult({
id: item.id.videoId,
title: item.snippet.title,
description: item.snippet.description,
thumbnailUrl: item.snippet.thumbnails.high.url
});
});
});
}
}

如果要用POST方式的话,也有http.post方法。

makePost(): void {
this.loading = true;
this.http.post(
'http://jsonplaceholder.typicode.com/posts',
JSON.stringify({
body: 'bar',
title: 'foo',
userId: 1
}))
.subscribe((res: Response) => {
this.data = res.json();
this.loading = false;
});
}

当然还有http.put,http.patch,http.delete以及http.head方法。

ng-book札记——HTTP的更多相关文章

  1. 【码在江湖】前端少侠的json故事(中)ng的json

    ng的json 正所谓"人在江湖,身不由己",在开发之路上前端少侠dk遇到过种种困难,尤其在与后端进行数据对接的时候,不得不逼迫自己以极快的速度去学习和掌握一些奇招怪式,正当他以为 ...

  2. 不知道张(zhāng)雱(pāng)是谁?你out了!

    张(zhāng)雱(pāng)是谁?也许你已经听说过了,也许你还没听说过呢,不过你一定听说过老刘——刘强东,没错,这二人是有关系的,什么关系,京东是老刘的,而张雱呢?张雱是京东旗下52家关联公司法人代 ...

  3. Flume NG Getting Started(Flume NG 新手入门指南)

    Flume NG Getting Started(Flume NG 新手入门指南)翻译 新手入门 Flume NG是什么? 有什么改变? 获得Flume NG 从源码构建 配置 flume-ng全局选 ...

  4. matlab基础教程——根据Andrew Ng的machine learning整理

    matlab基础教程--根据Andrew Ng的machine learning整理 基本运算 算数运算 逻辑运算 格式化输出 小数位全局修改 向量和矩阵运算 矩阵操作 申明一个矩阵或向量 快速建立一 ...

  5. 汇编语言标志位 含义 NV UP EI NG NZ AC PE CY

    缩写原意: Overflow of = OV NV [No Overflow] Direction df = DN (decrement) UP (increment) Interrupt if = ...

  6. 走进AngularJs(二) ng模板中常用指令的使用方式

    通过使用模板,我们可以把model和controller中的数据组装起来呈现给浏览器,还可以通过数据绑定,实时更新视图,让我们的页面变成动态的.ng的模板真是让我爱不释手.学习ng道路还很漫长,从模板 ...

  7. 第一次部署Struts2时出现错误java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.class

    报如下错误 at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720) at org. ...

  8. 汇编语言标记寄存器标记位_NV UP EI NG NZ AC PE CY

    在8086CPU中,有一种标记寄存器,长度为16bit: 其中存储的信息被称为程序状态字(Program Status Word,PSW),以下将该寄存器简称为flag. 功能:1)用来存储相关指令的 ...

  9. 高可用Hadoop平台-Flume NG实战图解篇

    1.概述 今天补充一篇关于Flume的博客,前面在讲解高可用的Hadoop平台的时候遗漏了这篇,本篇博客为大家讲述以下内容: Flume NG简述 单点Flume NG搭建.运行 高可用Flume N ...

  10. Python札记 -- 装饰器补充

    本随笔是对Python札记 -- 装饰器的一些补充. 使用装饰器的时候,被装饰函数的一些属性会丢失,比如如下代码: #!/usr/bin/env python def deco(func): def ...

随机推荐

  1. Beautifulsoup4

    kindEditor 1 官网:http://kindeditor.net/doc.php 2 文件夹说明: ├── asp asp示例 ├── asp.net asp.net示例 ├── attac ...

  2. 申请安装阿里云免费SSL证书

    微信小程序已经全面要求使用HTTPS服务了,还有苹果商店也是,所以,实现网站HTTPS已经很有必要.要实现HTTPS就需要一个SSL证书,证书大部分都很贵,不过也有一些免费的证书服务供个人开发者使用. ...

  3. 常见web安全隐患及解决方案

    Abstract 有关于WEB服务以及web应用的一些安全隐患总结资料. 1. 常见web安全隐患 1.1.       完全信赖用户提交内容 开发人员决不能相信一个来自外部的数据.不管它来自用户提交 ...

  4. Java 嵌套类基础详解

    目录 1. 什么是嵌套类? 2. 为什么要使用嵌套类? 3. 嵌套类的类型 4. 静态嵌套类 5. 非静态嵌套类 5.1 成员内部类 5.2 局部内部类 5.3 匿名内部类 6. 嵌套接口 1. 什么 ...

  5. [LeetCode] Longest Word in Dictionary 字典中的最长单词

    Given a list of strings words representing an English Dictionary, find the longest word in words tha ...

  6. [LeetCode] Count Binary Substrings 统计二进制子字符串

    Give a string s, count the number of non-empty (contiguous) substrings that have the same number of ...

  7. [LeetCode] Kill Process 结束进程

    Given n processes, each process has a unique PID (process id) and its PPID (parent process id). Each ...

  8. Mysql之基本操作与数据类型

    进入mysql: mysql -hlocalhost -uroot -p; mysql -uroot -p密码; 查看帮助文档: help 查看名 database(s); 创建数据库: create ...

  9. MYSQL时间盲住

    mysql注释 -- ,-- -,#,--+等 常用的判断语句: ' and if(1=0,1, sleep(10)) # " and if(1=0,1, sleep(10)) --+ ) ...

  10. 将python代码打印成pdf

    将python代码打印成pdf,打印出来很丑,完全不能看. mac下:pycharm 编辑器有print的功能,但是会提示: Error: No print service found. 所以需要一个 ...