Answer the question
In order to leave comments, you need to log in
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: 'Вася'}
})
}
Answer the question
In order to leave comments, you need to log in
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);
}
Only with pens, the typescript will not fix it for you.
// Класс здесь не нужен. Старайтесь предпочитать интерфейсы классам если у объекта нет методов
export interface NameSurName {
name: string;
surname: string;
}
...
this.nameSurName = {
name: '',
surename: 'Иванов',
...resp.data
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question