投不投 [英] Cast not casting

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

问题描述

我做了一个简单的Http调用:

I made a simple Http call:

http.get('/test/data/user.json').
    map(res => <User> res.json()).
    subscribe(user => {
        console.log(typeof user);
        console.log(user);
        console.log(user.getName());
});

,其中user.json中包含以下数据:

with the following data in user.json:

{
    "name":"Robert"
}

和以下User类:

export class User{
    name:string;
    lastName:string;
    getName():string{
        return this.name;
    }
}

问题是我进入控制台的结果:

Problem is the result I get in console:

console.log(typeof user);

对象

console.log(user);

对象{name:" Robert"}

Object {name: "Robert"}

console.log(user.getName());

未捕获的TypeError:user.getName不是函数

Uncaught TypeError: user.getName is not a function

问题

这里的问题是我的对象是object,而不是User,因此它没有所有属性,也没有方法.

Problem

Problem here is that my object is an object, not a User, so it does not have all properties, and it has no methods.

还尝试了基于Promise的呼叫和user.json() as User而不是<User> res.json()

Also tried with Promise-based call and user.json() as User instead of <User> res.json()

与强制转换为接口不一样,因为接口没有自己的行为.

not similar to casting to an interface since interface doesn't have its own behaviour.

推荐答案

如果要使用getName方法,则在映射响应主体时需要实例化一个新的User对象:

If you want to use the getName method, you need to instantiate an new User object when mapping the response body:

http.get('/test/data/user.json').
  map(res => {
    let body = res.json();
    return new User(body.name, body.lastName);
  })
  subscribe(user => {
    console.log(typeof user);
    console.log(user);
    console.log(user.getName());
  });

User类将进行如下修改:

export class User{
  constructor(private name:string, private lastName:string) {}

  getName():string{
    return this.name;
  }
}

投射对象不会将方法添加到现有对象.响应的json方法将仅使用JSON.parse解析响应主体并返回原始对象.

Casting an object won't add method to an existing object. The json method of the response will simply parse the response body using JSON.parse and return a raw object.

请参阅以下代码: https://plnkr.co/edit/7lKHvArpayrMAzm5Xgk1?p=preview .

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

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