I have the following code
export class MyComponent implements OnInit, AfterViewInit {
public list: any;
public anotherList: any;
constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
http.get<MyInterface[]>(baseUrl + 'api/Sample/DoSomething').subscribe(result => {
this.list = result;
this.anotherList = this.list;
cosole.log(result);
});
}
ngOnInit() {
}
ngAfterViewInit() {
}
}
The http
service returns the value in the constructor. However I want to move some code from constructor into ngOnInit
, say
ngOnInit() {
this.anotherList = this.list;
console.log(this.anotherList);
}
In chrome dev tools I found it is undefined. So I think it is the famous this
issue. I tried to use arrow function.
ngOnInit = () => {
this.anotherList = this.list;
console.log(this.anotherList);
}
But it was not called at all. I use angular 5.