[Angular2] service via Http Rxjs 用法

在 service 用http 去要資料(json)

然後給component 用


1. get data via Http
/* employee.service.ts*/
------------------------------------
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http'; //import Http, Headers 
import 'rxjs/add/operator/map'; //import rxjs

@Injectable()
export class EmployeeService {

    private _url: string = "../apidata/employeeData.json";

    constructor(private _http: Http) {}

    getEmployees(){ 
        return this._http.get(this._url)
                .map(res => res.json());
    } 

}



2.subscribe
/* employee-list.component.ts*/
-----------------------------------------------
import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../employee.service';


@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})

export class EmployeeListComponent implements OnInit {
    employees = [];

    constructor(private _empService: EmployeeService) { }

    ngOnInit() { 
        this._empService.getEmployees()
            .subscribe(resEmpData => this.employees = resEmpData);
    }


}


沒有留言:

張貼留言

蔡松霖
Related Posts with Thumbnails