我有以下界面:
export interface Data {
getText(): string;
}
两个类实现了提到的接口:
export class LocalStorageData implements Data {
public getText(): string {
return localStorage.getItem('data');
}
}
export class HttpData implements Data {
public constructor(private http: Http) {
}
public getText(): string {
let text = '';
this.http.get('http://server.com:3000/data').subscribe((response) => {
text = response.toString();
});
return text;
}
}
有一个类使用LocalStorageData
和HttpData
类:
export class Main {
private http: Http;
...
private getData(fromLocalStorage: boolean): Data {
let data: Data;
if (fromLocalStorage)
data = new LocalStorageData();
else
data = new HttpData(this.http);
return data;
}
public getText() {
console.log(this.getData(true).getText());
console.log(this.getData(false).getText());
}
}
当调用来自getText()
类的Main
时,第二个控制台日志将打印一个空字符串,因为来自get()
服务的Http
方法是异步的。
如何使用Data
service中的异步方法实现Http
接口?
答案 0 :(得分:-1)
更改界面
来自
export interface Data {
getText(): string;
}
到
export interface Data {
getText(): Observable<string>;
}
并从本地存储返回
Observable.of(localStorage.getItem('data'))
来自HttpData
export class HttpData implements Data {
public constructor(private http: Http) {
}
public getText(): Observable<string> {
let text = '';
return this.http.get('http://server.com:3000/data').map(res => res.json());
}
}
并按如下方式使用
public getText() {
this.getData(true).subscribe(test=> {
console.log(text);
})
this.getData(false).subscribe(test=> {
console.log(text);
})
}