angular2学习笔记之服务和http

现在应用开发多为spa的前后分离,前后端通讯则使用http的接口通过json进行交互。angular2-demo

一、 效果图

1. 展现出来的效果

2. mysql的数据

二、代码实例

1. 服务 service

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import {Injectable} from '@angular/core';
import { Http }from '@angular/http';
import * as api from './../api/Api';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class UserService {
    data:any;

    constructor(public http:Http) {
        this.http = http;
    }

    findAll():Observable<any> {
        return this.http.get(api.findAll).map((res:any)=> {
            return res.json();
        });
    }
}

2.组件 HttpService

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import {Component,OnInit} from '@angular/core';
import { UserService } from './../../service/UserService';


@Component({
    selector: 'http-service',
    styles:[require('./HttpService.scss')],
    template: require('./HttpService.html'),
    providers: [UserService]
})

export class HttpServiceComponent implements OnInit {

    admins:Object;
    data:Object;

    constructor(public userService:UserService) {
        this.userService = userService;
    }


    ngOnInit():void{
        this.userService.findAll().subscribe((data:any) => {
            this.admins = data.adminUsers.content;
            console.log('in component : ',this.admins);
        });
        console.log(' HttpServiceComponent ngOnInit :', 'enter');
    }

}

3. 模板 HttpService.html

1
2
3
<ul *ngFor="let item of admins;let i = index">
    <li>{{i+1}}.{{item.userName}}</li>
</ul>
署名 - 非商业性使用 - 禁止演绎 4.0