zoukankan      html  css  js  c++  java
  • ng-book札记——HTTP

    Angular拥有自己的HTTP库,可以用于调用外部API。

    在JavaScript世界里有三种方式可以实现异步请求,Callback,Promise与Observable。Angular倾向于使用Observable方式。

    HTTP库属于Angular中独立的模块,这意味着当使用时需要导入它。

    import {
        // The NgModule for using @angular/http
        HttpModule,
    
        // the class constants
        Http,
        Response,
        RequestOptions,
        Headers
    } from '@angular/http';
    

    举个基本的HTTP请求例子:

    import { Component, OnInit } from '@angular/core';
    import {Http, Response} from '@angular/http';
    
    @Component({
        selector: 'app-simple-http',
        templateUrl: './simple-http.component.html'
    })
    export class SimpleHttpComponent implements OnInit {
        data: Object;
        loading: boolean;
    
        constructor(private http: Http) {
        }
    
        ngOnInit() {
        }
    
        makeRequest(): void {
            this.loading = true;
            this.http.request('http://jsonplaceholder.typicode.com/posts/1')
            .subscribe((res: Response) => {
                this.data = res.json();
                this.loading = false;
            });
        }
    }
    

    http.request返回一个Observable,通过subscribe订阅变化。

    如果是想要用GET方式请求API的话,可以使用HTTP库中的http.get方法。

    @Injectable()
    export class YouTubeSearchService {
        constructor(private http: Http,
        @Inject(YOUTUBE_API_KEY) private apiKey: string,
        @Inject(YOUTUBE_API_URL) private apiUrl: string) {
    }
    
        search(query: string): Observable<SearchResult[]> {
            const params: string = [
            `q=${query}`,
            `key=${this.apiKey}`,
            `part=snippet`,
            `type=video`,
            `maxResults=10`
            ].join('&');
            const queryUrl = `${this.apiUrl}?${params}`;
            return this.http.get(queryUrl)
                .map((response: Response) => {
                    return (<any>response.json()).items.map(item => {
                        // console.log("raw item", item); // uncomment if you want to debug
                            return new SearchResult({
                            id: item.id.videoId,
                            title: item.snippet.title,
                            description: item.snippet.description,
                            thumbnailUrl: item.snippet.thumbnails.high.url
                    });
                });
            });
        }
    }
    

    如果要用POST方式的话,也有http.post方法。

    makePost(): void {
        this.loading = true;
        this.http.post(
        'http://jsonplaceholder.typicode.com/posts',
            JSON.stringify({
                body: 'bar',
                title: 'foo',
                userId: 1
            }))
            .subscribe((res: Response) => {
                this.data = res.json();
                this.loading = false;
        });
    }
    

    当然还有http.put,http.patch,http.delete以及http.head方法。

  • 相关阅读:
    让IIS支持解析.json格式文件
    请问4-20位字符可由中文,英文,数字及“—”,“-”组成 正则表达式
    jquery中的$(document).ready(function(){})和$(window).load()比较
    根据数组对象的某个属性值找到指定的元素
    JS数组中的indexOf方法
    bat修改注册表
    生动详细解释javascript的冒泡和捕获
    Jquery Easyui与Jquery Bootstrap的比较
    缺少的文件是 ..packagesMicrosoft.Net.Compilers.1.0.0uildMicrosoft.Net.Compilers.props。
    C#中ToString()格式详解
  • 原文地址:https://www.cnblogs.com/kenwoo/p/8904188.html
Copyright © 2011-2022 走看看