ng-book札记——HTTP
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的更多相关文章
- 【码在江湖】前端少侠的json故事(中)ng的json
ng的json 正所谓"人在江湖,身不由己",在开发之路上前端少侠dk遇到过种种困难,尤其在与后端进行数据对接的时候,不得不逼迫自己以极快的速度去学习和掌握一些奇招怪式,正当他以为 ...
- 不知道张(zhāng)雱(pāng)是谁?你out了!
张(zhāng)雱(pāng)是谁?也许你已经听说过了,也许你还没听说过呢,不过你一定听说过老刘——刘强东,没错,这二人是有关系的,什么关系,京东是老刘的,而张雱呢?张雱是京东旗下52家关联公司法人代 ...
- Flume NG Getting Started(Flume NG 新手入门指南)
Flume NG Getting Started(Flume NG 新手入门指南)翻译 新手入门 Flume NG是什么? 有什么改变? 获得Flume NG 从源码构建 配置 flume-ng全局选 ...
- matlab基础教程——根据Andrew Ng的machine learning整理
matlab基础教程--根据Andrew Ng的machine learning整理 基本运算 算数运算 逻辑运算 格式化输出 小数位全局修改 向量和矩阵运算 矩阵操作 申明一个矩阵或向量 快速建立一 ...
- 汇编语言标志位 含义 NV UP EI NG NZ AC PE CY
缩写原意: Overflow of = OV NV [No Overflow] Direction df = DN (decrement) UP (increment) Interrupt if = ...
- 走进AngularJs(二) ng模板中常用指令的使用方式
通过使用模板,我们可以把model和controller中的数据组装起来呈现给浏览器,还可以通过数据绑定,实时更新视图,让我们的页面变成动态的.ng的模板真是让我爱不释手.学习ng道路还很漫长,从模板 ...
- 第一次部署Struts2时出现错误java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.class
报如下错误 at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720) at org. ...
- 汇编语言标记寄存器标记位_NV UP EI NG NZ AC PE CY
在8086CPU中,有一种标记寄存器,长度为16bit: 其中存储的信息被称为程序状态字(Program Status Word,PSW),以下将该寄存器简称为flag. 功能:1)用来存储相关指令的 ...
- 高可用Hadoop平台-Flume NG实战图解篇
1.概述 今天补充一篇关于Flume的博客,前面在讲解高可用的Hadoop平台的时候遗漏了这篇,本篇博客为大家讲述以下内容: Flume NG简述 单点Flume NG搭建.运行 高可用Flume N ...
- Python札记 -- 装饰器补充
本随笔是对Python札记 -- 装饰器的一些补充. 使用装饰器的时候,被装饰函数的一些属性会丢失,比如如下代码: #!/usr/bin/env python def deco(func): def ...
随机推荐
- logback打印日志时添加上下文
尝试上述特性, 配置如下: 效果:
- MyBatis(一):配置并使用
MyBatis具体是什么东东,这些在后边在研究吧,本文目的是为了记录如何使用MyBatis. 首先,需要下载MyBatis开发所需要文件. 通过github上可以找到MyBatis代码:https:/ ...
- Canvas-自由绘制
#自由绘制 from tkinter import * master=Tk() c=Canvas(master,width=400,height=200) c.pack() def paint(eve ...
- 一览Django框架(转载)
本文面向:有python基础,刚接触web框架的初学者. 环境:windows7 python3.5.1 pycharm专业版 Django 1.10版 pip3 一.Django简介 百度百 ...
- drupal8之分类
示例: 我的相册 一.创建分类 1.创建一个相册 点击[结构]>[Taxonomy]>[+add vocabulary] 点击[保存] 2.创建相册的分类 点击[+add term] 点击 ...
- ActiveMQ(七)_伪集群和主从高可用使用(转)
本文转自: https://www.cnblogs.com/gossip/p/5977489.html 一.本文目的 介绍如何在同一台虚拟机上搭建高可用的Activemq服务,集群数量 ...
- 初学Servlet之实现Servlet接口
package app01a;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.Servlet;im ...
- 修改Execl中sheet名的指定字符串为指定字符串
Sub test() Dim sheet_count As Integer Dim sheet_name, new_sheet_name, old_str, new_str As String she ...
- HDU3311Dig The Wells
给定N个寺庙,和M个另外的地方. 然后给定点权,表示在这个点挖水井需要的代价. 再给定边权,为建造无向边i,j的代价. 然后求怎样弄最小的代价使得前N个点,就是寺庙都能从挖的井里得到水. 输入输出格式 ...
- ●BZOJ 2694 Lcm
题链: http://www.lydsy.com/JudgeOnline/problem.php?id=2694 题解: 莫比乌斯反演 不难看出,造成贡献的(i,j)满足gcd(i,j)无平方因子. ...