0

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.

Hello
  • 796
  • 8
  • 30
  • 4
    What do you mean *"the famous `this` issue"*? I think it's the famous *async* issue - is `this` undefined, or is `this.list`? – jonrsharpe Mar 12 '20 at 00:09
  • `console.log(this.anotherList);`"In chrome dev tools I found it is undefined." : your title suggest that `this` is undefined. However, here it seems that `anotherList` is undefined. which one is it ? which _exact_ (copy paste) message you get from the dev tools console ? – Pac0 Mar 12 '20 at 00:11
  • 1
    Also, it is considered bad practice to call your service/API in the constructor. You should do the `http.get().subscribe()` in your `ngOnInit` – Pac0 Mar 12 '20 at 00:12
  • I meant that `this.anotherList` is undefined. https://github.com/microsoft/TypeScript/wiki/'this'-in-TypeScript – Hello Mar 12 '20 at 00:13
  • `anotherList` is undefined because `list` is undefined, because you set it in an async function which doesn't complete until after `ngOnInit` runs. It has nothing to do with `this`. – John Montgomery Mar 12 '20 at 00:15
  • But I can get `this.list` in constructor. Why? – Hello Mar 12 '20 at 00:17
  • @Hello Because when you log it in the constructor, you're doing it from inside the `subscribe`. – John Montgomery Mar 12 '20 at 00:18
  • @Hello you need to wait unitl api response, before that you assign in ngOnInit. It throws undefined value. – Arunkumar Ramasamy Mar 12 '20 at 00:18

0 Answers0