在建構函式中使用 Http 的 Student Service 方法示例

import {Http} from '@angular/http';
@Injectable()
export class StudentService{
    constructor(public http: Http){}
    getAllStudents(): Observable<Students[]>{
        return this.http.get('assets/students.json')
        .map(res => res.json().data)     
        }
    }

現在再次注意建構函式如果我們想要使用這個服務方法,我們將轉到我們的檢視/頁面並:

import {StudentService} from './student.service';
import { SocialSharing } from '@ionic-native/social-sharing';
export class HomePage implements OnInit {

  constructor(public _studentService: StudentService, public socialSharing: SocialSharing) {
   }

再次注意這裡的建構函式,我們在建構函式中建立了一個 StudentService 例項,還有一件事,我們使用的是 socialSharing 外掛,所以我們也在建構函式中建立它的例項。