我是Angular2和Rxjs的新手,我对特定情况有些困惑。

我有一个简单的服务:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
import { Http, Response } from '@angular/http';

export interface Article {
  id: number;
  title: string;
  content: string;
  author: string;
}

@Injectable()
export class ArticleService {
  private _articles$: Subject<Article[]>;
  private baseUrl: string;
  private dataStore: {
    articles: Article[]
  };
  constructor(private http: Http) {
    this.baseUrl = 'http://localhost:3000'
    this.dataStore = { articles: [] };
    this._articles$ = <Subject<Article[]>>new Subject();
  }
  get articles$(){
    return this._articles$.asObservable();
  }

  loadAll(){
    //Observable.from(this.dummyData)
    this.http.get(`${this.baseUrl}/articles`)
    .map(response => response.json())
    .subscribe(data => {
      //debugger;
      this.dataStore.articles = data;
       // Push a new copy of our article list to all Subscribers.
      this._articles$.next(this.dataStore.articles)
    }, error => console.log('Could not load Articles'));
  }
}

并且这可以按预期工作,但是我想做的是能够在没有api终结点的情况下开发我的服务,并使用Observable进行开发,以后可以将其替换为http.request。我试图使用Observable.from将虚拟数据数组转换为可观察的数据,但是我得到了错误



我相信这是因为它是分别返回每个项目而不是返回数组,有人可以向我指出该如何工作的正确方向

更新:
为了清楚起见,dummyData看起来像:
private dummyData = [
      {
        id: 1,
        title: 'Title 1',
        content: 'content 1',
        author: 'author 1'
      },
      {
        id:2,
        title: 'Title 2',
        content: 'content 2',
        author: 'author 1'
      }
    ];

最佳答案

更新1

https://angular.io/guide/deprecations#http



原始

您可以使用 MockBackend



更新

定义dummyData像这样:

private dummyData = {
  json: function() {
    return [
      {
        id: 1,
        title: 'Title 1',
        content: 'content 1',
        author: 'author 1'
      },
      {
        id:2,
        title: 'Title 2',
        content: 'content 2',
        author: 'author 1'
      }
    ]};
}

关于javascript - 没有编写api时如何在Angular2中模拟可观察的http,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38058141/

10-10 07:40