dea*_*xes 4 arrays http reactive-programming rxjs angular
我正在使用Angular 2的http服务来获取一些数据,API返回'n'个结果,但我只想处理'x'数量.
考虑到我无法访问API的端点(为了创建limit或findOne类方法),我正在尝试找出最好的方法来处理将返回给调用我的组件的结果数量HomeService的"loadLatest"方法.
在这个特定的例子中,响应是一个看起来像这样的对象:
{
success: true,
data: [Object, Object, Object],
user: 'testUser'
}
Run Code Online (Sandbox Code Playgroud)
我只对数据数组感兴趣(比如,只获取它包含的前两个对象).
如果我想得到一个结果,我可以这样做:
import { Http, Headers } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
const URL = 'http://exampleapi.com/example';
@Injectable()
export class HomeService {
constructor(private _http: Http){}
loadLatest() {
return this._http.get(URL)
.map(res => res.json())
.map(({data}) => data[0]);
}
}
Run Code Online (Sandbox Code Playgroud)
它起作用(这并不一定意味着它确实没问题)......但是,我知道必须有一种更好的方法来返回,例如,响应对象中数据数组中的前两个对象.或前三个,或四个...或者我想要的多少.
我读到了关于"take"的方法,但我不相信它会在这种情况下真正起作用......
这是我订阅它并在我的组件中使用服务的地方:
import { Component, OnInit } from '@angular/core';
import { HomeService } from './home.service';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'home',
templateUrl: './home.html'
})
export class HomeComponent implements OnInit {
// I used this typing because I originally only wanted a single item
// This might have to change
items: Observable<Object>
constructor(private homeService: HomeService){}
ngOnInit() {
this.homeService.loadLatest()
.subscribe(result => this.items = result);
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我希望结果是一个包含两个对象的数组,我将它分配给this.items,这样我就可以使用angular的*ngFor迭代这两个对象.
任何帮助将不胜感激!提前致谢!
您可以slice在数据数组中使用该方法.
loadLatest() {
return this._http.get(URL)
.map(res => res.json())
.map(({data}) => data.slice(0,2));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3949 次 |
| 最近记录: |