简体   繁体   English

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

[英]Not a function error on TypeScript object after Casting

I made an http call using Angular5 http client.我使用 Angular5 http 客户端进行了 http 调用。 In map function I have done the casting of the response to a PersonModel.在 map 函数中,我已经完成了对 PersonModel 的响应的转换。

PersonModel has a function getFullName() which returns first_name + last_name PersonModel 有一个函数 getFullName() 返回 first_name + last_name

After doing the casting when I try to access this method on casted person object this shows an error of getFullName is not a function.当我尝试在强制转换的 person 对象上访问此方法进行强制转换后,这显示 getFullName 不是函数的错误。

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

}

This is the service这是服务

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

Error core.js:1350 ERROR TypeError: person.getFullName is not a function错误core.js:1350 错误类型错误:person.getFullName 不是函数

Log for object:对象的日志:

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

However when I create an object like this:但是,当我创建这样的对象时:

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

then this logs as this:然后记录如下:

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

Well , wellcome to JS/TS world.好吧,欢迎来到 JS/TS 世界。

When you cast basically it is just to avoid type "errors" on your IDE in typescript, and to be sure certain attributes exist on the object but not functions...当您基本上进行转换时,只是为了避免在打字稿中的 IDE 上键入“错误”,并确保对象上存在某些属性而不是函数...

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 

Hope this helps.希望这会有所帮助。

Try this:试试这个:

get(id: number): Observable<PersonModel> {
   return this.http.get('customer/' + id).pipe(
      map(p:any=> {return new PersonModel(p.first_name,p.middle_name,p.last_name)});
   );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM