加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – HttpClient没有运行构造函数

发布时间:2020-12-17 07:49:25 所属栏目:安全 来源:网络整理
导读:我正在使用HttpClient从json端点获取一个对象.在我获取它并订阅了observable后,我发现构造函数不在模型上运行,并且对象上的公共方法都是未定义的.如何让构造函数运行并且方法可用? export class Customer { constructor() { this.Addresses = new ArrayAddr
我正在使用HttpClient从json端点获取一个对象.在我获取它并订阅了observable后,我发现构造函数不在模型上运行,并且对象上的公共方法都是未定义的.如何让构造函数运行并且方法可用?
export class Customer {

    constructor() {
        this.Addresses = new Array<Address>();
        }

    public Addresses: Array<Address>;

    public addAddress(address: Address) void{
        this.Addresses.push(address);
    }
}

var url: string = `${this.urlBase}api/customer/${id}`;
var customerObservable: Observable<Customer> = this.authHttp.get<Customer>(url);

customerObservable.subscribe(customer => {
    // Addresses is undefined!
    customer.Addresses.push(new Address());
    // addAddress is undefined!
    customer.addAddress(new Address());
});
从.get返回的数据是Customer类的形状(假设您具有未显示的属性).但实际上并不是您的Customer类的实例.

这就是您无法访问任何Customer类方法的原因.

您必须使用new关键字创建Customer实例,然后将get中的数据复制到其中.

像这样的东西:

let customerInstance = Object.assign(new Customer(),customer);

然后,您将创建一个新的客户实例,您的构造函数将执行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读