Angular2 http.get(),map(),subscribe()和可观察模式 - 基本理解 [英] Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

查看:5625
本文介绍了Angular2 http.get(),map(),subscribe()和可观察模式 - 基本理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我有一个初始页面,其中有三个链接。单击最后一个朋友链接后,将启动相应的朋友组件。在那里,
我想获取/获取我的朋友的列表,这些朋友被列入了friends.json文件。
直到现在一切正常。但我仍然是使用RxJs的observables,map,subscribe concept的angular2的HTTP服务的新手。我试着理解它并阅读了一些文章,但在我开始实际工作之前,我不会理解这些概念。

Now, I have an initial page where I have three links. Once you click on the last 'friends' link, appropriate friends Component gets initiated. In there, I want to fetch/get list of my friends strored into friends.json file. Till now everything works fine. But I'm still a newbie for angular2's HTTP service using RxJs's observables, map, subscribe concept. I've tried to understand it and read few articles but until I get into practical work, I'm not gonna understand those concepts properly.

这里我已经做了plnkr除了与HTTP相关的工作外,它正在工作。

Here I have already made plnkr which is working except HTTP related work.

Plnkr

myfriends.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.

       }
  }

请正确指导和解释。我知道这对许多新开发者来说是非常有益的。

Please guide and explain properly. I know it will be so beneficial to lots of new developers.

推荐答案

这是你出错的地方:

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-您将observable本身分配给 this.result 。当你真的想要将朋友列表分配给 this.result 时。正确的方法是:

1- You assigned the observable itself to this.result. When you actually wanted to assign the list of friends to this.result. The correct way to do it is:


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

  • you subscribe to the observable. .subscribe is the function that actually executes the observable. It takes three callback parameters as follow:

.subscribe(成功,失败,完成);

例如:

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

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

Usually, you take the results from the success callback and assign it to your variable. the error callback is self explanatory. the complete callback is used to determine that you have received the last results without any errors. On your plunker, the complete callback will always be called after either the success or the error callback.

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

2- The second mistake, you called .json() on .map(res => res.json()), then you called it again on the success callback of the observable. .map() is a transformer that will transform the result to whatever you return (in your case .json()) before it's passed to the success callback you should called it once on either one of them.

这篇关于Angular2 http.get(),map(),subscribe()和可观察模式 - 基本理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆