现在,我有一个初始页面,在那里我有三个链接。一旦您单击最后的“friends”链接,适当的朋友组件就会被初始化。在那里,我想获取存储在friends.json文件中的我的朋友列表。
到目前为止,一切都运行良好。但我对于使用RxJs的observable、map、subscribe概念的angular2的HTTP服务仍然是一个新手。我尝试理解它并阅读了一些文章,但直到我实际操作才能正确理解这些概念。
在这里,我已经制作了一个工作正常(除了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.
}
}
请正确地指导和解释。我知道这对许多新开发人员会非常有益。
getFriends(){return http.get('friends.json').map(r => r.json());}
。现在,你可以调用getFriends().subscribe(...)
而不需要每次都调用.json()
。 - Abdulrahman Alsoghayerresult
只是一個參數名稱。您可以使用任何喜歡的名稱替換它。您可以將其寫成.subscribe(a=>this.result= a.json)
。這完全相同。 - Abdulrahman Alsoghayer