小编典典

Angular2 http.get() ,map(), subscribe() 和 observable 模式 - 基本理解

all

现在,我有一个初始页面,其中包含三个链接。单击最后一个“朋友”链接后,将启动适当的朋友组件。在那里,我想获取/获取存储在 friends.json
文件中的朋友列表。到目前为止,一切正常。但是我仍然是使用 RxJs 的 observables、map、subscribe 概念的 angular2 的
HTTP 服务的新手。我试图理解它并阅读了几篇文章,但在我开始实际工作之前,我不会正确理解这些概念。

在这里,我已经制作了除 HTTP 相关工作外的 plnkr。

PLNKR

我的朋友.ts

 import {Component,View,CORE_DIRECTIVES} from 'angular2/core';
 import {Http, Response,HTTP_PROVIDERS} from 'angular2/http';
 import 'rxjs/Rx';
 @Component({
    template: `
    <h1>My Friends</h1>
    <ul>
      <li *ngFor="#frnd of result">
          {{frnd.name}} is {{frnd.age}} years old.
      </li>
    </ul>
    `,
    directive:[CORE_DIRECTIVES]
  })

  export class FriendsList{

      result:Array<Object>; 
      constructor(http: Http) { 
        console.log("Friends are being called");

       // below code is new for me. So please show me correct way how to do it and please explain about .map and .subscribe functions and observable pattern.

        this.result = http.get('friends.json')
                      .map(response => response.json())
                      .subscribe(result => this.result =result.json());

        //Note : I want to fetch data into result object and display it through ngFor.

       }
  }

请正确引导和解释。我知道这对许多新开发人员来说非常有益。


阅读 46

收藏
2022-08-15

共1个答案

小编典典

这是你出错的地方:

this.result = http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result.json());

它应该是:

http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result);

或者

http.get('friends.json')
                  .subscribe(result => this.result =result.json());

你犯了两个错误:

1-您将可观察对象本身分配给this.result. 当您实际上想要将朋友列表分配给this.result. 正确的做法是:

  • 你订阅了 observable。.subscribe是实际执行 observable 的函数。它需要三个回调参数,如下所示:

.subscribe(success, failure, complete);

例如:

.subscribe(
    function(response) { console.log("Success Response" + response)},
    function(error) { console.log("Error happened" + error)},
    function() { console.log("the subscription is completed")}
);

通常,您从成功回调中获取结果并将其分配给您的变量。错误回调是不言自明的。完整的回调用于确定您已收到最后的结果,没有任何错误。 在您的 plunker
上,将始终在成功或错误回调之后调用完整的回调。

2-第二个错误,你调用.json().map(res => res.json()),然后你在 observable 的成功回调上再次调用它。
.map()是一个转换器,它将在将结果传递给成功回调之前将结果转换为您返回的任何内容(在您的情况下.json()),您应该在其中任何一个上调用它一次。

2022-08-15