Angular 2 HTTP requests with Promise

Source: Internet
Author: User
Tags export class

The first step: Simulate the RESTful API, or take the list of heroes as an example. (I used the node+express simulation, disable the same-origin policy) nothing to say directly on the code.

var express = require (' Express ');

var app = Express ();

Set a cross-domain access

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", "*"); Set the cross-domain access mode two

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 ("Application instance, Access address: http://%s:%s", host, Port)

})

The results are shown in chrome test.

Step two: Define the hero structure (HERO.TS)

Export Class Hero {

Id:number;

name:string;

Constructor (_id:number, _name:string) {

This.id = _id;

THIS.name = _name;

}

}

Step three: Writing Heroic services (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

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);

}

}

Fourth Step: Component Invocation (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 ();

}

}

The template file (app.component.html) is as follows:

<ul class= "Heroes" >

<li *ngfor= "Let Hero of Heroes" >

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

</li>

</ul>

Fifth Step: How it works in Chrome:

Angular 2 HTTP requests with Promise

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.