Angular 4 Http 服务


Http Service 将帮助我们获取外部数据,发布到它等等。我们需要导入 http 模块以使用 http 服务。让我们考虑一个例子来了解如何使用 http 服务。

要开始使用 http 服务,我们需要将模块导入到 app.module.ts 如下所示:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        HttpModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

如果你看到突出显示的代码,我们已经从 @angular/http 导入了 HttpModule,并且同样也添加到了 imports 数组中。

现在让我们在 app.component.ts .

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

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

export class AppComponent {
    constructor(private http: Http) { }
    ngOnInit() {
        this.http.get("http:// jsonplaceholder.typicode.com/users")。
        map((response) ⇒ response.json()).
        subscribe((data) ⇒ console.log(data))
    }
}

让我们理解上面突出显示的代码。我们需要导入http来使用该服务,具体操作如下:

import { Http } from '@angular/http';

在课堂里 应用组件 ,创建一个构造函数和 Http 类型的私有变量 http。要获取数据,我们需要使用 get API 可与 http 一起使用,如下所示

this.http.get();

如代码所示,它将要获取的 url 作为参数。

我们将使用测试 url - https://jsonplaceholder.typicode.com/users 获取json数据。对获取的 url 数据映射和订阅执行两个操作。 Map 方法有助于将数据转换为 json 格式。要使用地图,我们需要导入相同的内容,如下所示:

import 'rxjs/add/operator/map';

映射完成后,订阅将在控制台中记录输出,如浏览器所示:

Console 输出 Of Map

如果你看到,json 对象将显示在控制台中。对象也可以显示在浏览器中。

对于要在浏览器中显示的对象,请更新代码 app.component.html and app.component.ts 如下:

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    constructor(private http: Http) { }
    httpdata;
    ngOnInit() {
        this.http.get("http:// jsonplaceholder.typicode.com/users")。
        map(
            (response) ⇒ response.json()
        ).
        subscribe(
            (data) ⇒ {this.displaydata(data);}
        )
    }
    displaydata(data) {this.httpdata = data;}
}

In app.component.ts ,使用 subscribe 方法,我们将调用 display data 方法并将获取的数据作为参数传递给它。

在显示数据方法中,我们将数据存储在一个变量 httpdata 中。数据显示在浏览器中使用 for 在这个 httpdata 变量上,这是在 app.component.html file.

<ul *ngFor = "let data of httpdata">
    <li>Name : {{data.name}} Address: {{data.address.city}}</li>
</ul>

json对象如下:

{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
   
    "address": {
        "street": "Kulas Light",
        "suite": "Apt. 556",
        "city": "Gwenborough",
        "zipcode": "92998-3874",
        "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
        }
    },
   
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
        "name": "Romaguera-Crona",
        "catchPhrase": "Multi-layered client-server neural-net",
        "bs": "harness real-time e-markets"
    }
}

该对象具有 id、name、username、email 和 address 等属性,内部包含街道、城市等以及与电话、网站和公司相关的其他详细信息。使用 for 循环,我们将在浏览器中显示名称和城市详细信息,如 app.component.html file.

这是显示在浏览器中的显示方式:

Using For-Loop Name City Details

现在让我们添加搜索参数,它将根据特定数据进行过滤。我们需要根据传递的搜索参数获取数据。

以下是在 app.component.html and app.component.ts files:

app.component.ts

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'app';
    searchparam = 2;
    jsondata;
    name;
    constructor(private http: Http) { }
    ngOnInit() {
        this.http.get("http:// jsonplaceholder.typicode.com/users?id="+this.searchparam)。
        map(
            (response) ⇒ response.json()
        ).
        subscribe((data) ⇒ this.converttoarray(data))
    }
    converttoarray(data) {
        console.log(data);
        this.name = data[0].name;
    }
}

For the get api ,我们将添加搜索参数 id = this.searchparam。 searchparam 等于 2。我们需要详细信息 id=2 从 json 文件。

app.component.html

{{name}}

浏览器是这样显示的:

Ervin Howell

我们已经对浏览器中的数据进行了控制台处理,这些数据是从 http 接收的。浏览器控制台中也会显示相同的内容。来自 json 的名称 id=2 显示在浏览器中。