我有一个通过 http 从服务中获取数据的组件,问题是我不想每次显示这个组件时都访问 API 后端。我希望我的服务检查数据是否在内存中,如果是,则返回一个带有内存中数组的 observable,如果不是,则发出 http 请求。
我的组件
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 发布,翻译遵循 CC BY-SA 4.0 许可协议
你就在那儿。如果您已经在内存中有数据,您可以使用
of
observable(相当于 RxJS 4 中的return/just
)。