HttpClient将帮助我们提供POST,GET相关方法,使用时需要导入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 { }
我们从 @angular/common/http 导入了 HttpClientModule。
我们将使用上面声明的httpclient模块从服务器获取数据,我们将在上一章中创建的服务中执行此操作,并在所需组件内使用数据。
myservice.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方法,该方法会返回数据。当我们在浏览器中签入时,控制台将显示如下数据:
让我们如下使用app.component.html中的数据-
<h3>Users Data</h3> <ul> <li *ngFor="let item of persondata; let i=index"< {{item.name}} </li> </ul>
输出
参考链接
https://www.learnfk.com/angular7/angular7-http-client.html
标签:Http,app,component,Angular7,myservice,Client,import,http,angular From: https://blog.51cto.com/u_14033984/8738628