Angular7 Http 客户端
HttpClient 将帮助我们获取外部数据,发布到它等等。我们需要导入 http 模块以使用 http 服务。让我们考虑一个例子来了解如何使用 http 服务。
要开始使用http服务,我们需要在app.module.ts中导入模块,如下图:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule , RoutingComponent} from './app-routing.module'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; import { SqrtPipe } from './app.sqrt'; import { MyserviceService } from './myservice.service'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective, RoutingComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { }
如果你看到突出显示的代码,我们已经导入了 HttpClient模块 from @角/普通/http 在导入数组中也添加了相同的内容。
我们将使用上面声明的 httpclient 模块从服务器获取数据。我们将在上一章创建的服务中执行此操作,并使用我们想要的组件中的数据。
我的服务.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class MyserviceService { private finaldata = []; private apiurl = "http:// jsonplaceholder.typicode.com/users"; constructor(private http: HttpClient) { } getData() { return this.http.get(this.apiurl); } }
添加了一个名为 getData 的方法,该方法返回为给定 url 获取的数据。
从app.component.ts调用getData方法如下:
import { Component } from '@angular/core'; import { MyserviceService } from './myservice.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 7 Project!'; public persondata = []; constructor(private myservice: MyserviceService) {} ngOnInit() { this.myservice.getData().subscribe((data) => { this.persondata = Array.from(Object.keys(data), k=>data[k]); console.log(this.persondata); }); } }
我们正在调用 getData 方法,它返回一个可观察的类型数据。 subscribe 方法用在它上面,它有一个箭头函数,里面有我们需要的数据。
当我们在浏览器中查看时,控制台显示数据如下图:
让我们使用 app.component.html 中的数据如下:
<h3>Users Data</h3> <ul> <li *ngFor="let item of persondata; let i = index"< {{item.name}} </li> </ul>