Angular2:将数组转换为 Observable

新手上路,请多包涵

我有一个通过 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 许可协议

阅读 616
2 个回答

你就在那儿。如果您已经在内存中有数据,您可以使用 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);
    }
}

原文由 Eric Martinez 发布,翻译遵循 CC BY-SA 3.0 许可协议

您也可以使用 Observable.of(resultArray);

来自 import { Observable } from 'rxjs;'

原文由 Harry Sarshogh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题