如果没有编写api,如何在Angular2中模拟一个http observable

jon*_*nie 10 javascript rxjs angular2-services angular

我是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'));
  }
}
Run Code Online (Sandbox Code Playgroud)

这可以按预期工作,但我想要做的是能够在没有api端点的情况下开发我的服务并使用一个Observable,我可以稍后换掉它http.request.我尝试使用Observable.from将虚拟数据数组转换为observable,但我得到了错误

Type '{ id: number; title: string; content: string; author: string; }' is not assignable to type 'Article[]'

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

更新:为清晰起见,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'
      }
    ];
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

更新 1

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

@ANGULAR/HTTP/TESTING 最接近替换 @ANGULAR/COMMON/HTTP/TESTING
MockBackend ==> HttpTestingController
MockConnection ==> HttpTestingController

原来的

您可以使用 MockBackend

import {BaseRequestOptions, Http} from '@angular/http';
import {MockBackend} from '@angular/http/testing';
it('should get some data', inject([AsyncTestCompleter], (async) => {
  var connection;
  var injector = Injector.resolveAndCreate([
    MockBackend,
    {provide: Http, useFactory: (backend, options) => {
      return new Http(backend, options);
    }, deps: [MockBackend, BaseRequestOptions]}]);
  var http = injector.get(Http);
  var backend = injector.get(MockBackend);
  //Assign any newly-created connection to local variable
  backend.connections.subscribe(c => connection = c);
  http.request('data.json').subscribe((res) => {
    expect(res.text()).toBe('awesome');
    async.done();
  });
  connection.mockRespond(new Response('awesome'));
}));
Run Code Online (Sandbox Code Playgroud)

更新

定义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'
      }
    ]};
}
Run Code Online (Sandbox Code Playgroud)

  • 所以随着你的添加和从`Observable.from(this.dummyData)` 到`Observable.create(()=&gt; { return this.dummyData} )` 的变化,我能够得到我想要的结果。谢谢 (4认同)
  • 事情可能已经改变了。使用 Angular 2.4.0,rxjs 5.1.0,这对我有用:`Observable.create(observer =&gt; {observer.next(this.dummyData); });` (2认同)