angular - Angular2: chuyển mảng thành Observable
Tôi có một thành phần lấy dữ liệu từ một dịch vụ thông qua http, vấn đề là tôi không muốn gọi API backend mỗi lần hiển thị thành phần này. Tôi muốn dịch vụ của mình kiểm tra nếu dữ liệu có trong bộ nhớ, nếu có, trả về một observable với mảng trong bộ nhớ, và nếu không, thực hiện yêu cầu http.
Thành phần của tôi
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
);
}
}
Dịch vụ của tôi
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');
}
}
Câu trả lời #1
Bạn đúng ở điểm đó. Nếu bạn đã có dữ liệu trong bộ nhớ, bạn có thể sử dụng of observable (tương đương với return/just trong 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);
}
}
Câu trả lời #2
import { of } from 'rxjs';
return of(this.contacts);
Câu trả lời số 3
Trong Angular7 chỉ cần đặt of(). Bất cứ thứ gì bạn đặt trong of() sẽ được chuyển thành observable. Ở đây, this.contacts được chuyển thành observable.
import { of } from 'rxjs';
getContacts() {
if (this.contacts != null) {
return of(this.contacts);
}
}
Câu trả lời #4
Một số người như tôi muốn nó khác đi, đó là từ string[] sang Observable<string>.
Đây là một ví dụ liên quan đến việc chuyển đổi:
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);
Hy vọng nó sẽ giúp được một số người khác.
