Mat*_*s17 52 http rxjs angular
我有一个组件通过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
);
}
}
Run Code Online (Sandbox Code Playgroud)
我的服务
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');
}
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*nez 73
你就在那里.如果已经有内存中的数据,则可以使用ofobservable(相当于return/justRxJS 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);
}
}
Run Code Online (Sandbox Code Playgroud)
Mo *_*sis 15
import { of } from 'rxjs';
return of(this.contacts);
Run Code Online (Sandbox Code Playgroud)
小智 11
在 angular7 中,只需将of(). 无论你在里面放什么,
of()都会变成可观察的。在这里,this.contacts转换为 observable。
import { of } from 'rxjs';
getContacts() {
if(this.contacts != null)
{
return of(this.contacts);
}
}
Run Code Online (Sandbox Code Playgroud)
有些像我这样的人想要的是不同的,从而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);
Run Code Online (Sandbox Code Playgroud)
希望它能帮助其他人.