admin管理员组文章数量:1303414
I'm new to both Angular2 and Rxjs and I am a little confused about a particular case.
I have a simple service:
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'));
}
}
And this works as expected , but what I would like to do is to be able to develope my service without a api endpoint and using an Observable that I can later swap out for the http.request
. I tried to do this using Observable.from to convert a dummy data array to an observable but I get the errors
Type '{ id: number; title: string; content: string; author: string; }' is not assignable to type 'Article[]'
I believe this is because it is returning each item separately instead of the array , can someone point me in the correct direction of how this should work
Update: for clarity the dummyData look like:
private dummyData = [
{
id: 1,
title: 'Title 1',
content: 'content 1',
author: 'author 1'
},
{
id:2,
title: 'Title 2',
content: 'content 2',
author: 'author 1'
}
];
I'm new to both Angular2 and Rxjs and I am a little confused about a particular case.
I have a simple service:
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'));
}
}
And this works as expected , but what I would like to do is to be able to develope my service without a api endpoint and using an Observable that I can later swap out for the http.request
. I tried to do this using Observable.from to convert a dummy data array to an observable but I get the errors
Type '{ id: number; title: string; content: string; author: string; }' is not assignable to type 'Article[]'
I believe this is because it is returning each item separately instead of the array , can someone point me in the correct direction of how this should work
Update: for clarity the dummyData look like:
private dummyData = [
{
id: 1,
title: 'Title 1',
content: 'content 1',
author: 'author 1'
},
{
id:2,
title: 'Title 2',
content: 'content 2',
author: 'author 1'
}
];
Share
edited Jun 13, 2017 at 16:45
royhowie
11.2k14 gold badges53 silver badges67 bronze badges
asked Jun 27, 2016 at 15:43
jonniejonnie
12.7k16 gold badges57 silver badges94 bronze badges
6
- I'm not sure the implementation you're looking for, but loadAll() could probably just be loadAll() { this._article$.next([Article, Article]); } – JacobS Commented Jun 27, 2016 at 15:54
- @JacobS so I was following along with coryrylan./blog/angular-2-observable-data-services and he has an api, I was just trying to figure how I could avoid a http request but to continue development using an Observable where I could just sub in the ` this.http.get('${this.baseUrl}/articles')` later with a straight swap – jonnie Commented Jun 27, 2016 at 16:33
-
You'll be subscribing to an observable either way. It won't care how the data is pushed into the observable. It should be a clean swap. If you want to retain the
this.http
call I would suggest the in-memory-api -npmjs./package/angular2-in-memory-web-api – JacobS Commented Jun 27, 2016 at 16:46 -
@JacobS the problem is if I
this.http.get('${this.baseUrl}/articles').map(response => response.json())
toObservable.from(this.dummyData)
I get the build error mentioned above i.e.Type '{ id: number; title: string; content: string; author: string; }' is not assignable to type 'Article[]'
– jonnie Commented Jun 27, 2016 at 17:02 -
Why do you name your var like this
_articles$
? – angry kiwi Commented Feb 22, 2017 at 10:04
1 Answer
Reset to default 5Update 1
From https://angular.io/guide/deprecations#http
@ANGULAR/HTTP/TESTING CLOSEST REPLACEMENT IN @ANGULAR/COMMON/HTTP/TESTING
MockBackend ==> HttpTestingController
MockConnection ==> HttpTestingController
Original
You can use 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')); }));
Update
Define the dummyData
like:
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'
}
]};
}
本文标签: javascriptHow can a mock a http observable in Angular2 for when no api is writtenStack Overflow
版权声明:本文标题:javascript - How can a mock a http observable in Angular2 for when no api is written - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741716098a2394118.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论