我对 Typescript 非常陌生,正在开发我的第一个基于 Electron 的应用程序。第一部分是使用来自 json Web 服务的结果填充本地数据库的类。
我获取数据的类如下,一个扩展类。在 getAll 中,如果我在 JSON.parse 之后输出正文,我可以在控制台中毫无问题地看到我的结果。
import * as typedHttpClient from "typed-rest-client/HttpClient";
abstract class Client<Id, Item> {
private url: string;
constructor(url: string) {
this.url = url;
}
public async getAll() {
const httpc: typedHttpClient.HttpClient = new typedHttpClient.HttpClient("pip-dev");
let body = await (await httpc.get(this.url)).readBody();
body = JSON.parse(body);
return body;
}
}
export default Client;
import { BASE_URI } from "../config";
import Client from "./client";
const URI = `${BASE_URI}/v2/achievements/daily`;
export interface IAchievementDaily {
id: number;
level: ILevel;
required_access: string[];
}
export interface ILevel {
min: number;
max: number;
}
export class AchievementsDailyClient extends Client<number, IAchievementDaily> {
constructor() {
super(URI);
}
}
export default new AchievementsDailyClient();
但是,当我使用以下代码从我的 Database 类调用它时,我只能获得 Promise:String 或 Object:Object 输出。
public getAchievementsDaily() {
const response = api.achievementsDaily.getAll();
response.then((result) => this.logInformation(result));
}
private logInformation(inf: any) {
if (inf) {
// tslint:disable-next-line:no-console
console.dir("Information : " + inf, { depth: null, colors: true });
}
}
据我所知,只有在我的 getAll 返回正文后才应调用 response.then 命令。我已经检查了多个教程,这是我所能得到的。
我显然错过了一些东西,因为这不应该这么难。我需要做些什么来以不同的方式解析结果?
最佳答案
在这一行:
console.dir("Information : " + inf, { depth: null, colors: true });
字符串连接正在调用
inf.toString()
, 转换 inf
到那个没用的[object Object]
在它到达 console.dir
之前的字符串.试试这个,你可能会看到你的数据:console.dir("Information : ", inf, { depth: null, colors: true });
关于typescript - 异步 typed-rest-client 和 promise 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51631715/