Thursday, September 17, 2020

Tìm hiểu Http Client trong Angular 7

Http Client trong Angular giúp chúng ta tìm nạp dữ liệu từ các serve hoặc api từ bên ngoài để thực hiện được điều này chúng ta cần import http module để sử dụng http service.

Việc đầu tiên để tìm hiểu được những tính năng của http client angular chúng ta phải khai báo và import trong file app.module.ts

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';

import { ChangeTextDirective } from './change-text.directive';

import { AppRoutingModule, RoutingComponet } from './app-routing.module';

import { HomeComponent } from './home/home.component';

import { AboutComponent } from './about/about.component';

import { MyServiceService } from './service/my-service.service';

import { NewHomeComponent } from './home/new-home/new-home.component';

import { HttpClientModule } from '@angular/common/http';


@NgModule({

  declarations: [

    AppComponent,

    ChangeTextDirective,

    HomeComponent,

    AboutComponent,

    RoutingComponet,

    NewHomeComponent

  ],

  imports: [

    BrowserModule,

    AppRoutingModule,

    HttpClientModule

  ],

  providers: [MyServiceService],

  bootstrap: [AppComponent]

})

export class AppModule { }

chúng ta phải import 

import { HttpClientModule } from '@angular/common/http';

Tiếp theo tạo một class service để lấy dữ liệu từ serve

myservice.service.ts

import { HttpClient, HttpClientModule } from '@angular/common/http';

import { Injectable } from '@angular/core';


@Injectable({

  providedIn: 'root'

})

export class MyServiceService {

  private finalData =[];

  private apiurl = "http://jsonplaceholder.typicode.com/users";

  constructor(private httpclient:HttpClient) {


   }

  showTodate(){

    let date= new Date();

    return date;

  }

  public getData(){

    return this.httpclient.get(this.apiurl)

  }

}

Trong class service chúng ta tạo một hàm trả về một object được lấy từ api

Trong newHomecomponent.ts chúng ta lại sử dụng service trong angular để thực hiện get data

this.myService.getData().subscribe((data =>{

     this.personData = Array.from(Object.keys(data),k=>data[k]);

     console.log(this.personData);

    }))

để hiện thị được dữ liệu lên giao diện web các bạn phải thiết lập nó và gọi ra

<ul>

    <li *ngFor="let person of personData; let i=index">

        <p>{{person.name}} - {{person.username}}</p>

    </li>

</ul>

Đây là kết quả của việc sử dụng http client trong angular:

Http Client trong Angular


No comments:

Post a Comment