Angular 2 HTTP Requests with Promise

第一步:模拟restful api,还是以英雄列表为例。(我用的是node+express模拟,禁用同源策略)没什么好说的直接上代码。

var express = require(‘express‘);

var app = express();

//设置跨域访问式一

app.all(‘*‘, function (req, res, next) {

res.header("Access-Control-Allow-Origin", "*");

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");

res.header("X-Powered-By", ‘ 3.2.1‘)

res.header("Content-Type", "application/json;charset=utf-8");

next();

});

app.get(‘/heroes‘, function (req, res) {

//res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问方式二

var ret_obj = [{ "id": 1, "name": "Jackie Chan" }, { "id": 2, "name": "Jet Li" }];

res.end(JSON.stringify(ret_obj));

})

var server = app.listen(8081, function () {

var host = server.address().address

var port = server.address().port

console.log("应用实例,访问地址为?:http://%s:%s", host, port)

})

chrome中测试下,结果见下图。

第二步:定义英雄结构(hero.ts)

export class Hero {

id: number;

name: string;

constructor(_id: number, _name: string) {

this.id = _id;

this.name = _name;

}

}

第三步:编写英雄服务(hero.service.ts)

import { Injectable } from ‘@angular/core‘;

import { Http } from "@angular/http";

import ‘rxjs/add/operator/catch‘;

import ‘rxjs/add/operator/toPromise‘;

import { Hero } from ‘./hero‘

@Injectable()

export class HeroService {

heroesUrl = "http://localhost:8081/heroes";

constructor(private http: Http) { }

GetHeores(): Promise<Hero[]> {

return this.http.get(this.heroesUrl)

.toPromise()

.then(response => { console.log("Get the heroes from the server side succeeded!"); return response.json() as Hero[] })

.catch(this.handleError);

}

private handleError(error: any): Promise<any> {

console.error(‘An error occurred‘, error); // for demo purposes only

return Promise.reject(error.message || error);

}

}

第四步:组件调用(hero.service.ts)

import { Component } from ‘@angular/core‘;

import { Hero } from ‘./hero‘

import { HeroService } from ‘./hero.service‘

@Component({

selector: ‘app-root‘,

templateUrl: ‘./app.component.html‘,

styleUrls: [‘./app.component.css‘],

providers: [HeroService]

})

export class AppComponent {

title = ‘Tour of Heroes‘;

heroes: Hero[];

selectedHero: Hero;

constructor(private heroService: HeroService) { }

getHeroes(): void {

this.heroService

.GetHeores()

.then(heroes => { this.heroes = heroes; console.log(heroes) });

}

ngOnInit(): void {

this.getHeroes();

}

}

模板文件(app.component.html)如下:

<h1>{{title}}</h1>

<h2>My Heroes</h2>

<ul class="heroes">

<li *ngFor="let hero of heroes">

<span class="badge">{{hero.id}}</span> {{hero.name}}

</li>

</ul>

第五步:chrome中的运行效果:

时间: 2024-08-03 19:24:50

Angular 2 HTTP Requests with Promise的相关文章

深入理解jQuery、Angular、node中的Promise

最初遇到Promise是在jQuery中,在jQuery1.5版本中引入了Deferred Object,这个异步队列模块用于实现异步任务和回调函数的解耦.为ajax模块.队列模块.ready事件提供基础功能.在用jQuery操作DOM的时候对Promise的使用欲不够强烈,最近学习node和Angular,需要用js写业务逻辑和数据操作代码的时候这种场景需求就出来了.一般来说事件适合在交互场景中运用,因为用户的行为本来就是分散的,而promise这样的流程控制适合在后台逻辑中处理业务. //j

形象的讲解angular中的$q与promise(转)

以下内容摘自http://www.ngnice.com/posts/126ee9cf6ddb68 promise不是angular首创的,作为一种编程模式,它出现在……1976年,比js还要古老得多.promise全称是 Futures and promises.具体的可以参见 http://en.wikipedia.org/wiki/Futures_and_promises . 而在javascript世界中,一个广泛流行的库叫做Q 地址是https://github.com/kriskowa

[Angular] Bind async requests in your Angular template with the async pipe and the &quot;as&quot; keyword

Angular allows us to conveniently use the async pipe to automatically register to RxJS observables and render the result into the template once the request succeeds. This has some drawbacks, especially if we want to bind the same data in multiple par

AngularJS promise的使用

<!doctype html> <html ng-app="myApp"> <head> <link rel="stylesheet" href="http://cdn.jsdelivr.net/foundation/4.3.2/css/foundation.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/an

Promise的前世今生和妙用技巧

浏览器事件模型和回调机制 JavaScript作为单线程运行于浏览器之中,这是每本JavaScript教科书中都会被提到的.同时出于对UI线程操作的安全性考虑,JavaScript和UI线程也处于同一个线程中.因此对于长时间的耗时操作,将会阻塞UI的响应.为了更好的UI体验,应该尽量的避免JavaScript中执行较长耗时的操作(如大量for循环的对象diff等)或者是长时间I/O阻塞的任务.所以在浏览器中的大多数任务都是异步(无阻塞)执行的,例如:鼠标点击事件.窗口大小拖拉事件.定时器触发事件

剖析Promise内部结构,一步一步实现一个完整的、能通过所有Test case的Promise类

本文写给有一定Promise使用经验的人,如果你还没有使用过Promise,这篇文章可能不适合你,建议先了解Promise的使用 Promise标准解读 1.只有一个then方法,没有catch,race,all等方法,甚至没有构造函数 Promise标准中仅指定了Promise对象的then方法的行为,其它一切我们常见的方法/函数都并没有指定,包括catch,race,all等常用方法,甚至也没有指定该如何构造出一个Promise对象,另外then也没有一般实现中(Q, $q等)所支持的第三个

深究angularJS系列 - 第三弹

深究angularJS系列 - 初识 深究angularJS系列 - 第二弹 深究angularJS系列 - 第三弹,我们一起深入探究angular的服务和自定义指令O(∩_∩)O~~ Angular服务 $http: $http是angular中的一个核心服务; $http利用浏览器的xmlhttprequest或JSONP与远程HTTP服务器进行交互; $http的支持多种method的请求,get.post.put.delete.jsonp等. 下面通过JSONP方法进行$http服务的使

promise和Angular中的 $q, defer

在ES6语法中,新出了promise构造函数, 可用来生成promise实例. Promise对象: 代表了未来某个将要发生的事件(通常是一个异步操作).有了promise对象, 可以将异步操作以同步的流程表达出来, 避免了层层嵌套的回调函数(俗称'回调地狱'). 在Angularjs中,对象deferred 实例也可以暴露派生的Promise 实例.以下将对此作简单描述: 1. $q: $q是Angular的一种内置服务,它可以使你异步地执行函数,并且当函数执行完成时它允许你使用函数的返回值(

ANGULAR JS PROMISE使用

Promise是一种模式,以同步操作的流程形式来操作异步事件,避免了层层嵌套,可以链式操作异步事件. 我们知道,在编写javascript异步代码时,callback是最最简单的机制,可是用这种机制的话必须牺牲控制流.异常处理和函数语义化为代价,甚至会让我们掉进出现callback大坑,而promise解决了这个问题.   下面实例是angularjs 的promise的实现方式: <!DOCTYPE html> <html ng-app="app"> <