Angular2 http.get(),map(),subscribe()和observable模式 – 基
现在,我有一个初始页面,我有三个链接。一旦你点击最后的“朋友”链接,适当的朋友组件启动。在那里,
我想获取/获取我的朋友的列表,进入friends.json文件。 到现在一切工作正常。但我仍然是一个新手角色的HTTP服务使用RxJs的observables,地图,订阅概念。我试图理解它,阅读了几篇文章,但直到我进行实际工作,我不会理解这些概念正确。 这里我已经做了plnkr这是工作除了HTTP相关的工作。 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. } } 请正确指导和解释。我知道这将对许多新的开发人员有利。
这里是你错了的地方:
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。正确的做法是: >你订阅了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")} ); 通常,从成功回调中获取结果并将其分配给变量。 2-第二个错误,你在.map(res => res.json())上调用了.json(),然后你再次在observable的成功回调上调用它。.map()是一个变换器,它会将结果转换为任何你返回的(在你的情况下.json()),然后传递给成功回调你应该在其中一个上调用它一次。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |