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方法。

  • 相关阅读:
    精简的网站reset 和 css通用样式库
    bootstrap使用心得及css模块化的初步尝试
    如何更高效地定制你的bootstrap
    OOCSS的概念和思路
    圣杯布局和双飞翼布局的作用和区别
    espcms简约版的表单,提示页,搜索列表页
    Sublime快捷键
    JavaScript——理解闭包及作用
    JavaScript——基本的瀑布流布局及ajax动态新增数据
    JavaScript——之对象参数的引用传递
  • 原文地址:https://www.cnblogs.com/kenwoo/p/8904188.html
Copyright © 2011-2022 走看看