【发布时间】:2017-01-04 22:07:14
【问题描述】:
正在使用 Angular2 进行一些实验,并对如何解决服务公开共享可观察对象的情况感到好奇。一个组件负责获取数据,另一个组件负责显示数据。这是一些代码:
负责获取数据的常用HttpService
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class Service {
subject = new Subject<string[]>;
observable$ = this.subject.asObservable();
constructor(private http: Http) {}
observable: Observable<string[]>;
get(link: string): Observable<string[]> {
this.observable$ = this.http.get('myapi.com')
.map((res: Response) => this.subject.next(res.json())
.catch(this.handleError);
return this.observable$;
}
/**
* Handle HTTP error
*/
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
负责获取数据的GetComponent
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Service } from '../shared/index';
@Component({
moduleId: module.id,
selector: 'get',
templateUrl: 'get.component.html',
providers: [Service],
})
export class GetComponent {
constructor(public service: Service) {}
submit() {
this.service.get(this.url).subscribe();
}
}
负责显示数据的DisplayComponent
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
@Component({
moduleId: module.id,
selector: 'display',
templateUrl: 'display.component.html'
})
export class DisplayComponent {
subscription: Subscription;
constructor(public service: Service) {}
ngOnInit() {
// the observable is undefined :(
this.subscription = this.service.observable$.subscribe(data => {
console.log(data);
},
error => {
// this never gets reached :(
})
}
ngOnDestroy() {
// prevent memory leak when component is destroyed
this.subscription.unsubscribe();
}
}
除了错误处理不适用于DisplayComponent,此设计工作正常。 HttpService 中的地图功能也不太正确this.subject.next(res.json()
此外,GetComponent 必须像这样this.service.get(this.url).subscribe();“订阅”似乎不太正确
设计这种东西的正确方法是什么?如何让DisplayComponent 观察HttpComponent 引发的错误
【问题讨论】:
标签: reactjs angular typescript reactive-programming rxjs