我有一个组件通过http获取服务中的数据,问题是我不想在每次显示此组件时都点击API后端。我希望我的服务能够检查数据是否在内存中,如果是,则返回一个带内存数组的observable,如果没有,则发出http请求。Angular2:将数组转换为Observable
我的组件
import {Component, OnInit } from 'angular2/core';
import {Router} from 'angular2/router';
import {Contact} from './contact';
import {ContactService} from './contact.service';
@Component({
selector: 'contacts',
templateUrl: 'app/contacts/contacts.component.html'
})
export class ContactsComponent implements OnInit {
contacts: Contact[];
errorMessage: string;
constructor(
private router: Router,
private contactService: ContactService) { }
ngOnInit() {
this.getContacts();
}
getContacts() {
this.contactService.getContacts()
.subscribe(
contacts => this.contacts = contacts,
error => this.errorMessage = <any>error
);
}
}
我的服务
import {Injectable} from 'angular2/core';
import {Http, Response, Headers, RequestOptions} from 'angular2/http';
import {Contact} from './contact';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class ContactService {
private contacts: Array<Contact> = null;
constructor (private http: Http) {
}
getContacts() {
// Check first if contacts == null
// if not, return Observable(this.contacts)? <-- How to?
return this.http.get(url)
.map(res => <Contact[]> res.json())
.do(contacts => {
this.contacts = contacts;
console.log(contacts);
}) // eyeball results in the console
.catch(this.handleError);
}
private handleError (error: Response) {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
它像一个魅力工作!非常感谢! – Mathius17
这可能是一个愚蠢的问题,但不能只缓存observable本身并调用.next()而不是缓存状态并在每次调用时重新创建observable? –
好点,我会试试。虽然我不是最好的,因为当我想迭代数组以返回一个特定键的联系人时 – Mathius17