开发学院

您的位置:首页>教程>正文

教程正文

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 { }

  请留意上面的代码,我们已经从@angular/common/http导入了HttpClientModule,并且同样的代码也添加到了imports数组中。

  我们将使用上面声明的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提取的数据。

  getData方法从app.component.ts调用,如下所示

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方法,它有一个箭头函数来显示我们需要的数据。

  当我们检查浏览器时,控制台显示如下所示的数据

get_data.jpg

  我们使用的app.component.html的数据如下

<h3>Users Data</h3>
<ul>
   <li *ngFor="let item of persondata; let i = index"<
      {{item.name}}
   </li>
</ul>

输出

users_data.jpg