我有一个通过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');
  }
}

推荐答案

你就在那里.如果内存中已经有数据,可以使用of个observable(相当于RxJS 4中的return/just个).

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);
    }
}

Angular相关问答推荐

元件不工作时的Angular 17属性 Select 器

带迭代的Angular 内容投影

AOS中的数据绑定--可能吗?

Angular 如何观察DOM元素属性的变化?

Angular 17:延迟加载带参数的独立组件?

nx serve正在忽略@angular/localize/init的导入"

错误TS2531:对象可能为空.论窗体数组控件

为什么Angular的ViewEncapsulation枚举有没有值为1的键?

如何从2个api获取数据并查看Angular material 表中的数据?

重新打开模态时 ng-select 中的重复值 - Angular

Angular APP_INITIALIZER 中的 MSAL 身份验证

在 kubernetes 上创建 Ingress 服务以将 springboot [后端] 连接到前端 [angular]

*ngIf 和 *ngFor 在 元素上使用

Angular 2: Debounce(ngModelChange)?

找不到模块'@angular/compiler'

如何提高 Angular2 应用程序的加载性能?

如何将一个组件放入Angular2中的另一个组件中?

Firestore 从集合中获取文档 ID

Angular2动态改变CSS属性

如何在 Angular 2 中跟踪路由?