W
W
waltaki2019-08-27 18:04:47
Angular
waltaki, 2019-08-27 18:04:47

Angular - Default Variable Values ​​Not Working?

Hello.
Here is an example:
I have

export class NameSurName {
  name: string;
  surname: string = 'Иванов'
}

export class NameSurName Component implements OnInit {
  private nameSurName: NameSurName;
  constructor(private http: HttpClient) {}
}

ngOnInit() {
  this.http.get('api/namesurname').subscribe((resp) => {
    this.nameSurName = resp.data // {name: 'Вася'} 
  })
}

If only the name field comes to me, from the api, then surname is undefined...((
Why is that? How to solve?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Pikat, 2019-08-27
@waltaki

HttpClient does not create classes, you need to call the constructor manually, for example via map

this.http.get('api/namesurname')
.pipe(
    map((resp) => resp.data.map(item => new NameSurName(item)),
}
.subscribe((resp) => {
    this.nameSurName = resp.data // {name: 'Вася'} 
  })

export class NameSurName {
  name: string;
  surname: string = 'Иванов'

constructor(props: Partial<NameSurName >) {
   Object.assign(this, props);
}

D
Demian Smith, 2019-08-27
@search

Only with pens, the typescript will not fix it for you.

// Класс здесь не нужен. Старайтесь предпочитать интерфейсы классам если у объекта нет методов
export interface NameSurName {
  name: string;
  surname: string;
}

...

this.nameSurName = {
  name: '',
  surename: 'Иванов',
  ...resp.data
}

To the question "why so" the answer is: typescript does not add any magic to the code. The final code compiled from a typescript in JS looks almost the same as with a typescript, only without types. In short, TS doesn't do the type conversion for you.
Here is the official playground from the creators. For the sake of interest, you can sometimes check what happens from your TS code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question