Angular 角度json到接口

Angular 角度json到接口,angular,interface,Angular,Interface,我已经为我的json响应创建了模型(通过接口): export interface Test { id: number; name: string; } 对于数据,我有一个变量: public test: Test; 但当我得到json响应时,有更多的参数,比如last_name,它不在接口中,我仍然可以在代码中使用它。如何强制转换此json响应以仅匹配我的模型 我尝试了断言,但它不起作用,我仍然可以访问所有其他属性。接口只有在编译时才知道。您可以改为使用类,通过在构造函

我已经为我的json响应创建了模型(通过接口):

export interface Test {
    id: number;
    name: string;
}
对于数据,我有一个变量:

  public test: Test;
但当我得到json响应时,有更多的参数,比如last_name,它不在接口中,我仍然可以在代码中使用它。如何强制转换此json响应以仅匹配我的模型


我尝试了断言,但它不起作用,我仍然可以访问所有其他属性。

接口只有在编译时才知道。您可以改为使用类,通过在构造函数中声明属性,在运行时可以知道这些类:

class Test {
  constructor(
    public id: number,
    public name: string
  ){}
}
然后,您可以创建一个函数,该函数将返回给定类的实例并用数据填充该实例:

function cast<T>(data: any, model: new (...args: any[]) => T ): T {
  const classInstance = new model();
  const classProps = Object.getOwnPropertyNames(classInstance);

  classProps.forEach(prop => classInstance[prop] = data[prop]);
  return classInstance;
}
function cast(数据:any,模型:new(…args:any[])=>T:T{
常量classInstance=新模型();
const classProps=Object.getOwnPropertyNames(classInstance);
forEach(prop=>classInstance[prop]=data[prop]);
返回类实例;
}
您可以使用此功能将收到的数据映射到给定的模型:

this.http.get<Test>('someUrl').map(res => cast(res, Test))
this.http.get('someUrl').map(res=>cast(res,Test))
我不能为一个接口做这件事,但是使用一个类来实现您想要做的事情是可能的

有角度[打字稿]
您应该只将指定的属性从json response复制到变量中可能的重复项,但如果我有20个属性,而response有40个,则很难手动编写。也许您可以迭代接口的属性并只分配这些属性,请参见,但这没有意义,那么,我应该如何为我的json响应建立一个模型呢?这将适用于任何深度的响应,即任何数量的嵌套。变量a={x:23,y:{p:234};
class Award {
  name = "";
  category = "";
}

this.httpClient.get<Awards>("./assets/configs/award.json").subscribe(($:Award) => {
  // Pass an instance of the Class, you wish to receive your response as
  console.log(this.takeWhatIsNecessary(new Award(), $));
});

// Breadth First Search
// This function will go through keys, in any depth, and copy
// property values from corresponding keys from Response
// Into the target value
// And returns the target
takeWhatIsNecessary(target, response) {
const stack = [];

if (!response || !target) {
  return response;
}

stack.push({
  r: response,
  t: target
});

while (stack.length > 0) {
   const obj = stack.shift();

   for (const key in obj.t) {
     if (obj.t.hasOwnProperty(key) && obj.r.hasOwnProperty(key)) {
       if (typeof obj.t[key] === "object") {
         stack.push({
           t: obj.t[key],
           r: obj.r[key]
         });
       }
       obj.t[key] = obj.r[key];
     }
   }
 }
 return target;
}