How to use/import http module?

前端 未结 13 2082
鱼传尺愫
鱼传尺愫 2020-11-27 16:40

I\'ve been playing with Angular 2 Quickstart.

How can I use/import http module in Angular 2?

I\'ve looked at Angular 2 Todo\'s.js, but it doesn\'t use the ht

相关标签:
13条回答
  • 2020-11-27 17:41

    Last update: May 11, 2016
    Angular version: 2.0.0-rc.2
    Typescript version: 1.8.10

    Live working example.

    A simple example of how to use the Http module with Observable:

    import {bootstrap} from '@angular2/platform-browser-dynamic';
    import {Component, enableProdMode, Injectable, OnInit} from '@angular/core';
    import {Http, Headers, HTTP_PROVIDERS, URLSearchParams} from '@angular/http';
    import 'rxjs/add/operator/map';
    
    const API_KEY = '6c759d320ea37acf99ec363f678f73c0:14:74192489';
    
    @Injectable()
    class ArticleApi {
      constructor(private http: Http) {}
      
      seachArticle(query) {
        const endpoint = 'http://api.nytimes.com/svc/search/v2/articlesearch.json';
        const searchParams = new URLSearchParams()
        searchParams.set('api-key', API_KEY);
        searchParams.set('q', query);
        
        return this.http
          .get(endpoint, {search: searchParams})
          .map(res => res.json().response.docs);
      }
      
      postExample(someData) {
        const endpoint = 'https://your-endpoint';
        const headers = new Headers({'Content-Type': 'application/json'});
        
        return this.http
          .post(endpoint, JSON.stringify(someData), { headers: headers })
          .map(res => res.json());
      }
    }
    
    @Component({
      selector: 'app',
      template: `<ul>
                    <li *ngFor="let article of articles | async"> {{article.headline.main}} </li>
                 </ul>`, 
      providers: [HTTP_PROVIDERS, ArticleApi],
    })
    class App implements OnInit {
      constructor(private articleApi: ArticleApi) { }
      
      ngOnInit() {
        this.articles = this.articleApi.seachArticle('obama');
      }
    }
    
    enableProdMode();
    bootstrap(App)
      .catch(err => console.error(err));

    0 讨论(0)
提交回复
热议问题