【问题标题】:Angular2 Quickstart tutorial - replace mock data with remote http data?Angular2 快速入门教程 - 用远程 http 数据替换模拟数据?
【发布时间】:2016-02-15 15:18:34
【问题描述】:

Q) 谁能用一个清晰​​的例子来解释如何实现这一点?

我在这里完成了使用 TypeScript 的 Angular2 教程:

https://angular.io/docs/js/latest/quickstart.html

我想替换mock-heroes.ts 并获取hero.service.ts 以获取真实的http 数据。例如。从这里:

http://jsonplaceholder.typicode.com/users

但 Google 尚未编写教程的下一部分。

我们将不胜感激!

【问题讨论】:

    标签: angularjs http service typescript angular


    【解决方案1】:

    您需要利用 Http 类。注入之后,就可以用它来异步获取数据了:

    @Component({
      template: `
        <ul>
         <li *ngFor="#user of users | async">{{user.name}}</lu>
        </ul>
      `
    })
    export class AppComponent {
      constructor(private http:Http) {
        this.users = this.http.get(
          'http://jsonplaceholder.typicode.com/users').map(res=>res.json());
      }
    }
    

    Angular2 在这个级别利用了 observables。您可以使用async 管道或订阅回调...

    在引导您的应用程序时不要忘记设置HTTP_PROVIDERS

    import {bootstrap} from 'angular2/platform/browser';
    import {HTTP_PROVIDERS} from 'angular2/http';
    import {AppComponent} from './app.component';
    
    bootstrap(AppComponent, [ HTTP_PROVIDERS ]);
    

    【讨论】:

    • 好的,但是我如何将它与调用“service.ts”文件中的方法的“component.ts”一起使用呢?还是必须在构造函数中完成?谢谢。
    • 这和你处理模块的方式有关。 SystemJS 负责在 import { something } from 'module' 时加载文件内容...
    • 对不起,我想你误解了我的问题。我将如何更改您的示例以使“getData”方法位于单独的服务中,并且例如在单击单独的“组件”中的按钮时调用它。就像我提到的教程的组织方式一样。
    • 对不起!我认为这个答案可以帮助你:stackoverflow.com/questions/34450131/…
    【解决方案2】:

    就像 Thierry 解释的那样,您需要引导 HTTP_PROVIDERS 并在您将执行 http 调用的组件/服务上导入 HTTP 类。记得在 index.html 中包含 http 和 rxjs javascripts。

    以下服务将模拟英雄数据替换为您的 json。

    import {Http} from 'angular2/http';
    import {Injectable} from 'angular2/core';
    import 'rxjs/Rx'; 
    
    @Injectable()
    export class HeroService {
      private _url = 'http://jsonplaceholder.typicode.com/users';
      constructor(private http: Http){}
      getHeroes() { 
        return this.http.get(this._url)
          .map(res => <any[]> res.json())
          .catch(function(err) {console.log("err")}) 
      }
    }
    

    为了更好地说明我的意思,我使用您提供的 Json 快速用 http.get 请求替换了 Heroes Mock 数据 plunker。希望这对您有所帮助。

    【讨论】:

    • 谢谢,在你的回答出现之前我已经接受了蒂埃里的回答,但也感谢你的努力和笨拙的例子。干杯。
    • 没问题,我只是想举个例子,以防其他人有类似的问题。干杯~
    猜你喜欢
    • 1970-01-01
    • 2011-04-18
    • 2023-03-31
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    相关资源
    最近更新 更多