Http與toPromise()


說明

  1. 利用angular2的Http物件,可對url發送request,傳回的是Observable物件
  2. 利用rxjs的toPromise(),可以將Observable轉為Promise物件

程式碼寫法:

import { Http } from "@angular/http";
import 'rxjs/add/operator/toPromise';
constructor(private http: Http) {
    this.http.get(URL)
      .toPromise()
      .then(res => console.log(res))
      .catch(err => console.log(err));
}

程式碼範例:

1.在src/assets/下建立data.json檔案,裡面內容如下

{
  "pageName": "Page App Component",
  "greeting": "Hello Angular2"
}

2.建立HttpService

ng g s http

3.在http.service.ts中的程式碼如下

import { Injectable } from '@angular/core';
import { Http } from "@angular/http";
import 'rxjs/add/operator/toPromise';

@Injectable()
export class HttpService {

  constructor(private http: Http) {}

  getData = (): Promise<any> => {
    return this.http.get('./assets/data.json')
      .toPromise()
      .then(res => Promise.resolve(res.json()))
      .catch(err => Promise.reject(err));
  }
}

4.在app.component.ts注入HttpService,並使用getData()方法為屬性"pageName"和"greeting"根據傳回的內容設定參數

pageName: string = "";
greeting: string = "";

constructor(private httpService: HttpService) { }

ngOnInit() {
  this.httpService.getData()
    .then((res) => {
      this.pageName = res.pageName;
      this.greeting = res.greeting;
    })
    .catch((err) => {
      console.log(err);
    });
}

5.更改app.component.html內html如下

<p>
  App works!
</p>
<p>
  Page Name = {{pageName}}
</p>
<p>
  Greeting = {{greeting}}
</p>

6.測試http://localhost:4200網頁內容

results matching ""

    No results matching ""