承诺不返回有效的类实例 [英] Promise not returning a valid class instance

查看:50
本文介绍了承诺不返回有效的类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习Typescript,对C#开发人员来说听起来有些奇怪,但我已经迷失了.

I've just started learning Typescript and I'm already lost in something that sounds really strange for a C# developer.

摘要::Promise<WsIdSessionResponse>返回具有与WsIdSessionResponse类相同字段的变量,但它不是有效的WsIdSessionResponse实例.

Summary: Promise<WsIdSessionResponse> returns a variable that has same fields of WsIdSessionResponse class but it's not a valid WsIdSessionResponse instance.

长话
我有这样的服务(我已经省略了一些对这个问题无用的东西),它消耗了不是我编写的JSON Web服务:

Long story
I have a service like this (I've omitted something useless for the problem) consuming a JSON webservice not written by me:

export class WsIdSessionService {
    constructor(private http: HttpClient) { }

    doLoginAsync(user: string, pwd: string): Promise<WsIdSessionResponse> {
        let params = new HttpParams();
        params = params.append('username', user);
        params = params.append('password', pwd);
        return this.http.get<WsIdSessionResponse>(this.apiUrl, {params: params})
            .toPromise());
    };

WsIdSessionResponse 类就是这样

export class WsIdSessionResponse {
    public status: number;
    public username: string;

    public isOk(): boolean {
        return this.status == 1;
    }
}

当我从WsIdSessionService检索数据时出现问题:

Problem comes when I retrieve data from WsIdSessionService:

var idSvc = this.wsIdSession.doLoginAsync(user, pwd);
var t = idSvc.then(info => {
    if (t.isOk()) {
      // Do something here
    }
}

执行t.isOk()时出现错误,告诉我isOk()不是函数!
什么?!?没有功能吗?是的,我班上有那个函数!

When I execute t.isOk() I get an error telling me that isOk() is not a function!
What?!? Not a function? Yes it is, I have that function in my class!

浪费了大量时间后,我终于想到了尝试这段代码

After wasting a huge amount of time, I finally thought about trying this code

var idSvc = this.wsIdSession.doLoginAsync(user, pwd);
var t = idSvc.then(info => {
    console.warn(`info is valid: ${info instanceof WsIdSessionResponse}`);
}

在这里我得到一个false作为结果:因此返回的变量具有我需要的类的相同字段,但是它不是该类的真实实例,这就是isOk()函数无效的原因!
但这怎么可能呢?我的意思是,http.get<WsIdSessionResponse>应该返回WsIdSessionResponse的有效实例,或者最终返回错误...我错了吗?

Here I get a false as result: so returned variable has same fields of the class I need but it's not a real instance of the class and that's the reason isOk() function is not valid!
But how is this possible? I mean, http.get<WsIdSessionResponse> should return a valid instance of the WsIdSessionResponse or eventually an error... am I wrong?

仅提供完整的信息:http.get<WsIdSessionResponse>从返回纯JSON字符串的URL中获取数据.

Just to provide complete infos: http.get<WsIdSessionResponse> gets data from a url returning a plain JSON string.

这是预期的行为还是我做错了什么?

Is this the expected behaviour or am I doing something wrong?

推荐答案

<WsIdSessionResponse>不会使对象成为WsIdSessionResponse的实例.它欺骗打字系统以为它是一个实例并抑制类型错误. TypeScript是具有类型安全性的JavaScript,并且在编译时只是JavaScript.

<WsIdSessionResponse> doesn't make the object an instance of WsIdSessionResponse. It cheats typing system to think that it is an instance and suppresses type errors. TypeScript is JavaScript with type safety, and it is just JavaScript when it's compiled.

除非使用new显式创建WsIdSessionResponse的实例,否则该对象将保留在Object中,而没有isOk方法.

Unless an instance of WsIdSessionResponse is created explicitly with new, the object will stay Object, with no isOk method.

它应该起作用的方式是:

The way it's supposed to work is:

interface IWsIdSessionResponse {
    status: number;
    username: string;
}

class WsIdSessionResponse implements IWsIdSessionResponse {
    public status: number;
    public username: string;

    public isOk(): boolean {
        return this.status == 1;
    }
}

...

doLoginAsync(user: string, pwd: string): Promise<WsIdSessionResponse> {
        ...
        return this.http.get<IWsIdSessionResponse>(this.apiUrl, {params: params})
            .map(plainResponseObj => Object.assign(new WsIdSessionResponse, plainResponseObj))
            .toPromise());
    };

这篇关于承诺不返回有效的类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆