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

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

问题描述

现在,我有一个初始页面,其中包含三个链接.单击最后一个朋友"链接后,将启动相应的朋友组件.在那里,我想获取/获取存储到朋友.json 文件中的朋友列表.直到现在一切正常.但我仍然是使用 RxJs 的 observables、map、subscribe 概念的 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(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 上,完整的回调将始终在成功或错误回调之后调用.

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- 第二个错误,你在 .map(res => res.json()) 上调用了 .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() 和 observable 模式——基本理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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