Angular2: преобразовать массив в наблюдаемый
У меня есть компонент, который получает данные из службы через http, проблема в том, что я не хочу удалять API-сервер при каждом показе этого компонента. Я хочу, чтобы мой сервис проверял, находятся ли данные в памяти, если это так, верните наблюдаемый массив в память, а если нет, сделайте 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');
}
}
Ответы
Ответ 1
Ты здесь. Если у вас уже есть данные в памяти, вы можете использовать of
наблюдаемый (эквивалент return/just
в RxJS 4).
getContacts() {
if(this.contacts != null)
{
return Observable.of(this.contacts);
}
else
{
return this.http.get(url)
.map(res => <Contact[]> res.json())
.do(contacts => this.contacts = contacts)
.catch(this.handleError);
}
}
Ответ 2
import { of } from 'rxjs';
return of(this.contacts);
Ответ 3
Некоторые люди, подобные мне, хотят по-другому, от string[]
до Observable<string>
.
Это пример, который включает преобразование:
import { from } from 'rxjs/observable/from';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toArray';
const ids = ['x12', 'y81'];
let userUrls: string[];
from(ids) // Converting string[] into Observable<string>
.map(id => 'http://localhost:8080/users/' + id)
.toArray()
.subscribe(urls => userUrls = urls);
Надеюсь, это поможет некоторым другим.
Ответ 4
В angular7 достаточно просто поставить of()
. Все, что вы поместите of()
будет изменено на наблюдаемое. Здесь this.contacts
преобразуется в наблюдаемые.
import { of } from 'rxjs';
getContacts() {
if(this.contacts != null)
{
return of(this.contacts);
}
}
Ответ 5
Это может быть очень поздно, но я довольно часто использую sessionStorage для обработки некоторых моих работ. Если вы потеряете состояние, потому что люди подпрыгивали, у вас все еще есть ваши данные.
getSubjects(): Observable<Subject[]> {
let SubjectsString = sessionStorage.getItem("Subjects")
if (SubjectsString) {
let subjects: Subject[] = JSON.parse(SubjectsString);
console.log("GETTING DATA FROM SESSION STORAGE")
return Observable.of(subjects);
} else {
let url = `${this.apiHost}/api/subject`;
return this.http.get(url)
.map(res =>{
sessionStorage.setItem("Subjects",JSON.stringify(res.json()));
return res.json();
})
}
}
Ответ 6
Быстрое решение здесь:
getSomething():Observable<Object[]>{
return new Observable(observable => {
this.http.get('example.com').subscribe(results => {
observable.next(results.json());
observable.complete();
});
});
}
Ответ 7
Вы также можете использовать Observable.of(resultArray);
из import { Observable } from 'rxjs;'
пакет