gpt4 book ai didi

angular - 转换后不是 TypeScript 对象上的函数错误

转载 作者:太空狗 更新时间:2023-10-29 19:33:36 26 4
gpt4 key购买 nike

我使用 Angular5 http 客户端进行了一次 http 调用。在 map 函数中,我完成了对 PersonModel 的响应的转换。

PersonModel 有一个函数 getFullName() 返回 first_name + last_name

在执行转换后,当我尝试在转换的人对象上访问此方法时,显示错误 getFullName is not a function。

export class PersonModel {
constructor(
public first_name: string = null,
public middle_name: string = null,
public last_name: string = null) {

}

getFullName() {
return this.first_name + this.last_name;
}

}

这是服务

get(id: number): Observable<PersonModel> {
return this.http.get("customer/" + id)
.map((response: any) => {
return <PersonModel>response;
});
}


customerService.get(1).subscribe(result => {
console.log(result.getFullName());
})

错误core.js:1350 ERROR TypeError: person.getFullName 不是函数

对象日志:

{first_name: "kjlkj", last_name: "jnkjh"}

但是当我创建这样一个对象时:

const person = new PersonModel();
person.first_name = "lkj";
person.last_name= "lkj";

然后这个记录如下:

PersonModel {first_name: "kjlkj", last_name: "jnkjh"}

最佳答案

好吧,欢迎来到 JS/TS 世界。

当你基本上转换时,它只是为了避免在你的 IDE 中使用 typescript 输入“错误”,并确保对象上存在某些属性而不是函数......

class Dog {
public name: string = "";

bark(): void {
console.log("whoof whoof");
}
}


let johnny = new Dog();
johnny.name = "johnny";
johnny.bark(); // => Barks ok

let onlyattrs = {
name: "err"
} as Dog;

// onlyattrs.bark(); // => function does not exists

let realDog = new Dog();
realDog = Object.assign(realDog, onlyattrs);

realDog.bark(); // => barks ok

希望这对您有所帮助。

关于angular - 转换后不是 TypeScript 对象上的函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48346334/

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