Http service trong Angular 4 – Freetuts

Http Service giúp chúng ta thực hiện các phương thức GET, POST với dữ liệu thông qua giao thức HTTP. Để sử dụng Http Service, chúng ta cần import http module . Hãy cùng đi vào một vài ví dụ cụ thể để hiểu hơn về Http Service nhé.

test php

banquyen png

Bài viết này được đăng tại

freetuts.net

, không được copy dưới mọi hình thức.

Các bước sử dụng Http Service

Để sử dụng http service, trước tiên ta cần thực hiện 2 bước:

Bước 1: Import HttpClientModule vào module

Bước 2: Khai báo và sử dụng HttpClient trong component

Bài viết này được đăng tại [free tuts .net]

Ví dụ sử dụng http service

Trong ví dụ này, chúng ta sẽ lấy dữ liệu từ trang http://jsonplaceholder.typicode.com/users – một trang mockup dữ liệu cho chúng ta test, sau đó log ra console và hiển thị lên giao diện.

Import http service

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router'
// Import http module
import {HttpClientModule} from '@angular/common/http';

import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { FormsModule } from '@angular/forms';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
@NgModule({
  declarations: [
    AppComponent,
    NewCmpComponent,
    ChangeTextDirective,
    SqrtPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    // Khai báo http module
    HttpClientModule,
    RouterModule.forRoot([
      {
        path: 'new-cmp',
        component: NewCmpComponent
      }
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Sử dụng http service trong app component

Sửa nội dung của file app.component.ts như sau

app.component.ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

export class AppComponent {
    results;
    constructor(private http: HttpClient) { }
    ngOnInit() {
        this.http.get("http://jsonplaceholder.typicode.com/users").subscribe(data => {
             console.log(data);
            this.results = data;
        });
    }
}

Phương thức this.http.get() tạo ra 1 get request đến địa chỉ http://jsonplaceholder.typicode.com/users. Khi dữ liệu trả về, ta thực hiện xử lý dữ liệu thông qua phương thức subscribe

get và xử lý dữ liệu

 this.http.get("http://jsonplaceholder.typicode.com/users").subscribe(data => {
            console.log(data);
            this.results = data;
        });

Khi thực hiện được request xong thì phương thức subscribe chịu trách nhiệm xử lý tiếp. Ở đây, subscribe sẽ log dữ liệu ra console như hình dưới

Kết quả hiển thị ở console khi gọi service

Hiển thị dữ liệu ra view

Để hiển thị dữ liệu ra view, ta thực hiện 2 bước:

Bước 1: Khai báo  biến để chứa dữ liệu mà http service trả về.

Bước 2: Bind dữ liệu ra view

Ở phần trên, dữ liệu trả về của http service đã được lưu vào biến results. Giờ nhiệm vụ của chúng ta là hiển thị dữ liệu ấy ra.

Cùng nhìn vào dữ liệu của một bản ghi:

chi tiet ban ghi du lieu png

Dữ liệu có id, name, email, phone, username, website address. Address lại có các thuộc tính city, street, suite. Chúng ta sẽ hiển thị dữ liệu này dưới dạng bảng nhé.

Sửa nội dung file app.component.html

app.component.html

<h2>Dữ liệu lấy từ service</h2>
<table>
    <thead>
        <tr>
            <th>id</th>
            <th>name</th>
            <th>username</th>
            <th>phone</th>
            <th>address</th>
            <th>company</th>
        </tr>
    </thead>

    <tbody>
        <tr *ngFor="let user of results">
            <td>{{user.id}}</td>
            <td>{{user.name}}</td>
            <td>{{user.username}}</td>
            <td>{{user.phone}}</td>
            <td>
                <p>- Street: {{user.address.street}}</p>
                <p>- City: {{user.address.city}}</p>
                <p>- ZipCode: {{user.address.zipcode}}</p>
            </td>
            <td>
                <p>- Name: {{user.company.name}}</p>
                <p>- bs: {{user.company.bs}}</p>
                <p>- catchPhrase: {{user.company.catchPhrase}}</p>
            </td>
        </tr>
    </tbody>
</table>

Ta sử dụng kĩ thuật data binding đã học trong bài trước để bind dữ liệu từ mảng result ra view. Đối với companyaddress có các dữ liệu con bên trong nên ta sẽ hiển thị trên nhiều dòng của cùng một ô.

Chạy chương trình, ta thu được kết quả

Kết quả hiển thị dữ liệu ra view

Nội dung bài học về http service đến đây là hết rồi. Hẹn gặp lại bạn trong bài sau nhé.

Danh sách file tải về

Tên file tải về
Pass giải nén

Tải source code

freetuts.net hoặc gameportable.net