0

I am fairly new in Angular and have a problem connected with assigning a json response from server to new instantiated object.

I have a class MyClass

export class MyClass {
Id: number
}

obj: MyClass;
myService.fetch().subscribe(a=>obj=a);

The problem is, that response from server has five properties and when I assign this response to my object it got them all although this object has only one property "Id".

I am printing both this objects to console by

myService.fetch().subscribe(a=>{
obj=a
console.log(a);
console.log(obj);
}});

And I receive two the same objects. Why this happens? Shouldn't I be notified that assignment cannot be done, because there are missing properties on class MyClass?

justme
  • 316
  • 3
  • 13
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) –  Apr 03 '19 at 21:08

1 Answers1

0

What is the type of a ? If it isn't typed properly, Typescript can't detect the missmatch.

Shouldn't I be notified that assignment cannot be done, because there are missing properties on class MyClass?

No, there are additional properties on a. They don't change the way how your code does interact with obk, so there is no problem with assigning an object with more properties to a type with less. Typescript has duck typing after all (if something has an Id it is a MyClass).

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151