gpt4 book ai didi

javascript - 由接口(interface)强制执行的异步方法的顺序调用,Angular 4

转载 作者:搜寻专家 更新时间:2023-10-30 22:03:28 25 4
gpt4 key购买 nike

我有以下界面:

export interface Data {
getText(): string;
}

两个类实现了上述接口(interface):

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;
}
}

有一个类使用 LocalStorageDataHttpData 类:

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());
}
}

Main 类的 getText() 被调用时,第二个控制台日志将打印一个空字符串,因为 get() 方法来自 Http 服务是异步的。

如何使用 Http 服务的异步方法实现 Data 接口(interface)?

最佳答案

改变界面

来自

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);
})
}

关于javascript - 由接口(interface)强制执行的异步方法的顺序调用,Angular 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44971936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com