【问题标题】:Implementing a HTTP web request in Angular 2在 Angular 2 中实现 HTTP Web 请求
【发布时间】:2016-05-02 02:52:44
【问题描述】:

我一直在关注 Angular2 示例:https://angular.io/docs/ts/latest/tutorial/

我已经完成了对模拟英雄的承诺。不过,我想更进一步,尝试建立一个 http 请求,以从第 3 方来源获取英雄列表。

比如说,我设置了一个网址http://pastebin.com/raw/2mEEPeUs,它以示例中给出的格式将英雄列表返回为json。

实现这一点的最佳方法是什么?

通过查看Angular 2, Getting Data Out of Service,我认为这可能就像更新以下内容一样简单:

hero.service.ts

import {Hero} from './hero';
import {HEROES} from './mock-heroes';
import {Injectable} from 'angular2/core';
import {Http, Response, HTTP_PROVIDERS} from "angular2/http";

@Injectable()
export class HeroService {
constructor(public http: Http){}
  getHeroes(){
    return this.http.request('http://pastebin.com/raw/2mEEPeUs')
        .map(response => response.json());
  }
}

app.component.js

ngOnInit() {
  this.getHeroes().subscribe(
    res => this.heroes = res,
    err => this.logError(err));
}

【问题讨论】:

    标签: javascript ajax angular


    【解决方案1】:

    在这个 plunker 中,我创建了一个带有 http 请求的示例:http://plnkr.co/edit/qXwLNh6UHacmHhji80VR

    对我来说有 3 件困难的事情:

    1. 您应该添加到您的 index.html
    2. 您需要在 boot.ts 中将 HTTP_PROVIDERS 添加到注入器
    3. 需要将 rxjs/Rx 导入 hero 服务中

    代码如下: boot.ts

    import {bootstrap} from 'angular2/platform/browser';
    import {HTTP_PROVIDERS} from "angular2/http";
    import {App} from "./app.component";
    import {HeroService} from "./hero.service";
    
    bootstrap(App, [HeroService, HTTP_PROVIDERS]);
    

    英雄服务.ts

    import {Injectable} from 'angular2/core';
    import {Http} from 'angular2/http';
    import construct = Reflect.construct;
    import 'rxjs/Rx';
    
    @Injectable()
    export class HeroService {
    
    
        constructor(private _http : Http) {
    
        }
    
    
        public getHeroesAsObservable () {
            // reactive programming
            // https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
            //http://chariotsolutions.com/blog/post/angular2-observables-http-separating-services-components/
    
            return this._http.get('heroes').map(res => res.json());
    
        }
    
    }
    

    app.component.ts

    import {Component} from 'angular2/core';
    import {HeroDetailComponent} from "./hero-detail.component";
    import {HeroService} from "./hero.service";
    import {OnInit} from "angular2/core";
    
    @Component({
        selector: 'my-app',
        styles:[`
          .heroes {list-style-type: none; margin-left: 1em; padding: 0; width: 10em;}
          .heroes li { cursor: pointer; position: relative; left: 0; transition: all 0.2s ease; }
          .heroes li:hover {color: #369; background-color: #EEE; left: .2em;}
          .heroes .badge {
            font-size: small;
            color: white;
            padding: 0.1em 0.7em;
            background-color: #369;
            line-height: 1em;
            position: relative;
            left: -1px;
            top: -1px;
          }
          .selected { background-color: #EEE; color: #369; }
        `],
        template: `
            <h1>{{title}}</h1>
            <ul class="heroes">
                <li *ngFor="#hero of heroes"
                    (click)="onSelectHero(hero)"
                    [class.selected]="hero === selectedHero">
                    <span class="badge">{{hero.id}}</span> {{hero.name}}
                </li>
            </ul>
            <hero-detail [hero]="selectedHero"></hero-detail>
            `,
        directives:[HeroDetailComponent],
        //providers:[HeroService]
    })
    export class App implements OnInit{
        public title = 'Tours of Heroes';
        public heroes;
        public selectedHero : Hero;
    
        constructor(private _heroesService : HeroService) {
    
        }
    
        ngOnInit () {
            //this._heroesService.getHeroes().then(heroes => this.heroes = heroes);
    
            var observable = this._heroesService.getHeroesAsObservable()
                .subscribe(
                    data => this.heroes = data,
                    err => console.log('ERROR!!!', err)
                );
    
        }
    
        onSelectHero (hero : Hero) {
            this.selectedHero = hero;
        }
    
    }
    

    本地索引.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>tour of heroes tutorial Angular 2</title>
    
    
        <!-- 1. Load libraries -->
        <script src="../node_modules/angular2/bundles/angular2-polyfills.js"></script>
        <script src="../node_modules/systemjs/dist/system.src.js"></script>
        <script src="../node_modules/rxjs/bundles/Rx.js"></script>
        <script src="../node_modules/angular2/bundles/angular2.js"></script>
        <script src="../node_modules/angular2/bundles/http.dev.js"></script>
    
        <!-- 2. Configure SystemJS -->
        <script>
            System.config({
                packages: {
                    src: {
                        format: 'register',
                        defaultExtension: 'js'
                    }
                }
            });
            System.import('src/boot')
                    .then(null, console.error);
        </script>
    
    </head>
    <body>
        <my-app>Loading...</my-app>
    </body>
    </html>
    
    
    <html>
    

    添加异步管道是个好主意! 希望 plunker 对你有用

    【讨论】:

      【解决方案2】:

      您应该利用async 管道在模板中显示可观察对象。这样您就不必自己管理订阅:

      @Component({
        template: `
          <ul>
            <li *ngRepeat="hero of heroes | async">{{hero.name}}</li>
          </ul>
        `
      })
      export class MyComponent {
        ngOnInit() {
          this.heroes = this.getHeroes();  
        }
      }
      

      这个答案还可以为您提供一些关于在服务中实现 HTTP 请求并从组件中使用它们的方式的额外提示:

      希望对你有帮助 蒂埃里

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-24
        • 2016-11-17
        相关资源
        最近更新 更多